【发布时间】:2018-11-27 12:45:54
【问题描述】:
前段时间我写了一个自定义指令,现在在代码中的很多地方都使用它(不能再更改它了)。
它有一个公共范围,直到今天都很好。现在我想在同一个控制器作用域(父作用域)内使用相同的指令两次,但需要每个指令(子作用域)有自己的变量(如隔离作用域)并且彼此不匹配。
是否可以插入此指令并明确声明使用隔离范围,即使它首先是使用公共范围创建的? 或者可能是一种在父控制器内限制它的方法? 或者有没有其他方法可以做到?
例如
// Panel directive
angular.directive('panel', function(){
return {
restrict: 'E',
templateUrl: 'panel.html',
replace: true,
transclude: true
}
});
// Parent directive (include more than one 'panel' directives)
angular.directive('parentDirektive'), function() {
return {
restrict: 'E',
templateUrl: 'parent.html',
replace: true,
transclude: true,
scope: {},
controller: function($scope) {
// I want to set different value for this variable
// in each 'panel' direktive I add in 'parent.html'.
$scope.headline = 'this.should.be.unique.in.each.panel.directive';
}
}
});
父.html
我想以某种方式设置“scope.headline”的值 此处出现的每个面板都不同 (比如隔离每个指令中的变量)?! 但不能在声明中将范围更改为隔离 只有在这种情况下才需要它。
<html>
<body>
<!-- I want to display 'Title: First Panel' -->
<panel></panel>
<!-- I want to display 'Title: Second Panel' -->
<panel></panel>
</body>
</html>
panel.html
<html>
<body>
<h1>Title: {{$scope.headline}}</h1>
</body>
</html>
【问题讨论】:
-
当询问由您的代码引起的问题时,如果您提供人们可以用来重现问题的代码,您将获得更好的答案。见How to create a Minimal, Complete, and Verifiable example。指令范围可以是 none、inherited 或 isolate。不清楚您所说的“公共范围”是什么意思。
-
我用一些例子编辑了我的问题。谢谢
标签: angularjs angularjs-directive angularjs-scope angularjs-controller