我想了解指令中的隔离作用域。 我有以下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 指令:
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
这样的隔离指令的作用域中添加“本地”功能?这是示例。
有人可以解释一下这里发生了什么吗?谢谢!
scope:true
时继承子作用域)。隔离作用域旨在与可重用组件一起使用,并尝试在指令和控制器之间提供更多安全性 - 例如,避免作用域上的名称冲突。在第三种情况下,您需要一个自定义指令模板示例在此处。 - csharpfolkisolation-test
div 中,作用域实际上是父级作用域(与same-test
相同)。由于没有定义模板,因此无法访问隔离作用域。谢谢,我之前不理解模板和隔离作用域之间的关系。现在有了更清晰的认识。 - CSharp