【问题标题】:AngularJS directives - Isolated Scope and Inherited ScopeAngularJS 指令 - 隔离作用域和继承作用域
【发布时间】:2013-12-18 10:53:55
【问题描述】:

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

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

我缺少什么吗?

【问题讨论】:

    标签: angularjs


    【解决方案1】:

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

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

    检查this fiddle

    【讨论】:

    • 感谢@Reto,如果它从控制器继承属性,那么 v1.2 中的隔离范围有什么意义。
    • 关于指令内的模板。如果从myIsolatedDirective 中删除范围隔离,myProperty 将绑定到控制器范围。我认为 1.1.x 中的行为并不是 Vojta 所说的那样:“在应用程序模板或其他一些指令模板中定义的子元素不会获得隔离范围。理论上,没有人应该依赖这种行为,因为这种行为非常罕见——在大多数情况下,isolate 指令都有一个模板。”
    • 感谢@Reto 或解释。
    猜你喜欢
    • 2016-03-18
    • 1970-01-01
    • 1970-01-01
    • 2015-02-17
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多