【发布时间】:2016-04-06 02:18:47
【问题描述】:
我正在尝试理解指令中的独立作用域。我有以下html:
<div new-test>
<h4>new scope : {{msg}}</h4>
<button ng-click="clicker()">new test</button>
<hr>
</div>
<div same-test>
<h4>same as parent scope : {{msg}}</h4>
<button ng-click="clicker()">same test</button>
<hr>
</div>
<div isolate-test>
<h4>isolated scope : {{msg}}</h4>
<button ng-click="clicker()">isolated test</button>
<button ng-click="ftn()">own ftn</button>
<hr>
</div>
还有以下角度指令:
angular.module('myApp', []);
angular.module('myApp')
.directive('newTest', [function() {
return {
scope: true,
link: function(scope, elem, attr) {
scope.msg = 'new scope';
scope.clicker = function() {
console.log("New Scope");
};
}
}
}])
.directive('sameTest', [function() {
return {
scope: false,
link: function(scope, elem, attr) {
scope.msg = 'same scope';
scope.clicker = function() {
console.log("Same Scope");
};
}
}
}])
.directive('isolateTest', [function() {
return {
restrict: 'A',
scope: {},
link: function(scope, elem, attr) {
scope.msg = 'isolated scope'; // this doesn't exist
scope.clicker = function() {
console.log("Isolated Scope"); // this is never called
};
scope.ftn = function() {
console.log("own ftn"); // or this
};
}
}
}]);
我认为我添加到isolateTest 指令范围的函数或变量都不存在。如果我单击isolate test 按钮,则会调用same-test 指令中的clicker 函数。怎么会?我认为该按钮与 div 元素之间的任何其他元素一起存在于一个孤立的范围内?如何将“本地”函数添加到像 isolateTest 这样的独立指令的范围内?这是fiddle。
谁能解释一下这里发生了什么。谢谢!
【问题讨论】:
-
顾名思义,隔离范围仅在指令代码和模板中可见。您不将模板与指令一起使用,而是绑定在继承父范围(或在使用
scope: true时为子范围)的嵌套 HTML 元素上。隔离作用域被设计为与可重用组件一起使用,并试图在指令和控制器之间提供更高的安全性——例如避免范围上的名称冲突。在第三种情况下你想要的是一个自定义指令模板example here。 -
谢谢。所以在
isolation-testdiv 中,作用域实际上是父作用域(与same-test相同)。由于没有定义模板,因此无法访问隔离范围。谢谢,我之前不了解模板和隔离范围之间的关系。现在说得通了。
标签: javascript angularjs