gpt4 book ai didi

AngularJS 指令 - 隔离作用域和继承作用域

转载 作者:行者123 更新时间:2023-12-04 21:17:01 29 4
gpt4 key购买 nike

我一直在尝试理解指令中孤立作用域和继承作用域之间的区别。这是我准备让自己理解的一个例子:

HTML

<div ng-controller="AppController">
<div my-directive>
Inside isolated scope directive: {{myProperty}}
</div>

<div my-inherit-scope-directive>
Inside inherited scope directive: {{myProperty}}
</div>
</div>

JS
angular.module("myApp", [])
.directive("myInheritScopeDirective", function() {
return {
restrict: "A",
scope: true
};
})
.directive("myDirective", function() {
return {
restrict: "A",
scope: {}
};
})
.controller("AppController", ["$scope", function($scope) {
$scope.myProperty = "Understanding inherited and isolated scope";
}]);

使用 Angular-1.1.5 执行代码,它按我的预期工作: my-directive 中的 {{myProperty}} 将是 undefined由于隔离范围,而对于 my-inherit-scope-directive,{{myProperty}} 将具有值 Understanding inherited and isolated scope .

但是使用 Angular-1.2.1 执行,在两个指令 {{myProperty}} 输出 Understanding inherited and isolated scope .

有什么我想念的吗?

最佳答案

指令中的文本节点绑定(bind)到 Controller 范围。因此,该指令的范围无效。我认为这有 changed从 v1.2 开始。您必须为指令使用模板:

.directive("myIsolatedDirective", function () {
return {
template: 'Inside isolated in template scope directive: {{myProperty}}',
restrict: "A",
scope: {
myProperty: '='
}
};
})

查看 this fiddle .

关于AngularJS 指令 - 隔离作用域和继承作用域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20656168/

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