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

前端之家收集整理的这篇文章主要介绍了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",scope: {}
            };
        })
        .controller("AppController",["$scope",function($scope) {
            $scope.myProperty = "Understanding inherited and isolated scope";
        }]);

使用Angular-1.1.5执行代码,它按预期工作:由于隔离范围,my-directive中的{{myProperty}}将是未定义的,而对于my-inherit-scope-directive,{{myProperty}}将具有理解继承和隔离范围的价值.

但是在两个指令{{myProperty}}中使用Angular-1.2.1执行输出了解继承和隔离范围.

我错过了什么?

解决方法

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

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

检查this fiddle.

猜你在找的Angularjs相关文章