AngularJS指令 - 隔离范围和继承的范围 [英] AngularJS directives - Isolated Scope and Inherited Scope
问题描述
我一直在试图理解孤立的范围和继承指令的范围之间的差异。这是一个例子,我prepared让自己明白:
I've been trying to understand the difference between isolated scope and inherited scope in directive. This is an example I prepared to make myself understand:
的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";
}]);
执行的code。与角1.1.5,它的工作原理如我所料:本{{myProperty的}}内我的指令会是未定义
,因为孤立的范围,而对于我,继承范围的指导性,{{myProperty的}}将具有值理解继承和孤立的范围
。
Executing the code with Angular-1.1.5, it works as I expected: The {{myProperty}} inside my-directive will be undefined
because of isolated scope, whereas for my-inherit-scope-directive, {{myProperty}} will have the value Understanding inherited and isolated scope
.
但随着角1.2.1执行,在这两个指令{{myProperty的}}输出了解继承和孤立的范围
。
But executing with Angular-1.2.1, in both the directives {{myProperty}} outputs Understanding inherited and isolated scope
.
什么我失踪?
推荐答案
您的指令内的文本节点被绑定到控制器范围。因此该指令的范围没有任何影响。我觉得这改变为1.2版本。你必须使用一个模板为您的指令:
The text node inside your directive is bound to the controller scope. Therefore the scope of the directive has no effect. I think this has changed as of v1.2. You have to use a template for your directive:
.directive("myIsolatedDirective", function () {
return {
template: 'Inside isolated in template scope directive: {{myProperty}}',
restrict: "A",
scope: {
myProperty: '='
}
};
})
这篇关于AngularJS指令 - 隔离范围和继承的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!