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

Anu*_*eva 5 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>
Run Code Online (Sandbox Code Playgroud)

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";
        }]);
Run Code Online (Sandbox Code Playgroud)

使用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.

我错过了什么?

Ret*_*old 2

指令内的文本节点绑定到控制器范围。因此该指令的范围没有影响。我认为从 v1.2 开始这已经改变了。您必须为您的指令使用模板:

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

检查一下这个小提琴