我正在尝试理解指令中的隔离范围。我有以下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
按钮,则会调用clicker
指令中的same-test
函数。怎么会?我认为该按钮与div元素之间的任何其他元素一起存在于隔离范围内?如何将{local'函数添加到isolateTest
等隔离指令的范围内?这是fiddle。
有人可以解释一下这里发生了什么。谢谢!
答案 0 :(得分:1)
在isolateTest
指令中,我将您的scope: {}
切换为scope: true
,然后我就可以启动您的功能了。
更新了小提琴:https://jsfiddle.net/rjcmjd0k/11/
.directive('isolateTest', [function() {
return {
restrict: 'A',
scope: true,
link: function(scope, elem, attr) {
scope.msg = 'isolated scope';
scope.clicker = function() {
console.log("Isolated Scope");
};
scope.ftn = function() {
console.log("own ftn");
};
}
}
}]);