我很想了解指令中孤立作用域和继承作用域之间的区别。以下是我准备的一个例子,以帮助自己理解:
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>
The 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
。
我是否遗漏了什么?
myIsolatedDirective
中移除范围隔离,则myProperty
将绑定到控制器作用域。我认为1.1.x版的行为并非Vojta所说的意图:“应用模板或其他指令模板中定义的子元素不会获得隔离作用域。理论上,没有人应该依赖这种行为,因为它非常罕见——在大多数情况下,隔离指令都有一个模板。” - Reto Aebersold