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

5

我很想了解指令中孤立作用域和继承作用域之间的区别。以下是我准备的一个例子,以帮助自己理解:

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

我是否遗漏了什么?

1个回答

2

您指令内的文本节点绑定到控制器作用域。因此,指令作用域没有影响。我认为从v1.2开始已经发生了变化。您需要为指令使用模板:

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

Check this fiddle.


谢谢@Reto,那么如果它从控制器继承属性,v1.2中孤立作用域的意义是什么? - Anup Vasudeva
这是关于指令内模板的内容。如果从myIsolatedDirective中移除范围隔离,则myProperty将绑定到控制器作用域。我认为1.1.x版的行为并非Vojta所说的意图:“应用模板或其他指令模板中定义的子元素不会获得隔离作用域。理论上,没有人应该依赖这种行为,因为它非常罕见——在大多数情况下,隔离指令都有一个模板。” - Reto Aebersold
感谢 @Reto 的解释。 - Anup Vasudeva

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接