我的 angularJS 应用程序中有两个自定义指令。一个充当 parent ,另一个充当 child 。我正在尝试在子指令中访问父级的范围。但我没有得到所需的输出。
<div ng-controller="CountryCtrl">
{{myName}}
<div ng-controller="StateCtrl">
<state nameofthestate="'Tamilnadu'">
<city nameofthecity="'Chennai'"></city>
</state>
</div>
</div>
我的脚本看起来像
var app = angular.module("sampleApp",[]);
app.controller("CountryCtrl",function($scope){
$scope.myName = "India";
});
app.controller("StateCtrl",function($scope){
});
app.directive("state",function(){return {
restrict : 'E',
transclude: true,
scope : { myName : '=nameofthestate'},
template:"** {{myName}} is inside {{$parent.myName}}<br/><ng-transclude></ng-transclude>"
}});
app.directive("city",function(){return {
restrict : 'E',
require:'^state',
scope : { myName : '=nameofthecity'},
template:"**** {{myName}} is inside {{$parent.myName}} which is in {{$parent.$parent.myName }}<br/> "
}});
相应的 JSFiddle 在 https://jsbin.com/nozuri/edit?html,js,output 中可用
我得到的输出是
India
** Tamilnadu is inside India
**** Chennai is inside India which is in Tamilnadu
预期的输出是
India
** Tamilnadu is inside India
**** Chennai is inside Tamilnadu which is in India
谁能告诉我我在这里做错了什么?
最佳答案
city 指令 $parent 是 state 指令的嵌入范围。
state 指令的嵌入范围是为 $parent of state 指令继承的,它是 Controller ,因此这就是 $parent.MyName = India 的原因。
嵌入范围的 $parent 是状态指令隔离范围(scope = {}),这就是为什么 $parent.$parent.MyName = Tamilnadu(Angular 1.3 更新的一部分)
发生的事情的一些细节: How to access parent scope from within a custom directive *with own scope* in AngularJS?
transclude: true - the directive creates a new "transcluded" child scope, which prototypically inherits from the parent scope. If the directive also creates an isolate scope, the transcluded and the isolate scopes are siblings. The $parent property of each scope references the same parent scope.
Angular v1.3 update: If the directive also creates an isolate scope, the transcluded scope is now a child of the isolate scope. The transcluded and isolate scopes are no longer siblings. The $parent property of the transcluded scope now references the isolate scope.
Matthew 的答案对于亲子指令通信也是正确的。
关于javascript - 自定义子指令访问父级范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31200906/