gpt4 book ai didi

javascript - 在 Angular 中修改独立范围指令的范围

转载 作者:行者123 更新时间:2023-11-29 15:31:20 25 4
gpt4 key购买 nike

我试图理解指令中的独立作用域。我有以下 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 Directive(指令):

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 .

谁能解释一下这里发生了什么。谢谢!

最佳答案

在您的 isolateTest 指令中,我将您的 scope:{} 切换为 scope: true,并且我能够获取您的函数开火。

更新 fiddle :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");
};
}
}
}]);

关于javascript - 在 Angular 中修改独立范围指令的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34557788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com