AngularJS指令 - 隔离范围和继承范围

时间:2013-12-18 10:53:55

标签: angularjs

我一直试图理解指令中孤立范围和继承范围之间的区别。这是我准备让自己明白的一个例子:

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

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

我缺少什么?

1 个答案:

答案 0 :(得分:2)

指令中的文本节点绑定到控制器范围。因此该指令的范围无效。我认为从v1.2开始这个changed。您必须为指令使用模板:

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

检查this fiddle