javascript - 自定义子指令访问父级范围

标签 javascript angularjs angularjs-directive angularjs-scope

我的 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 更新的一部分)

enter image description here

发生的事情的一些细节: 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/

相关文章:

单击按钮后 JavaScript 取消 SetTimeout

jquery - 使用 jQuery 按类选择 Angular JS 指令中 ng-repeat 创建的元素?

javascript - Angularjs - 对象未传递到指令的范围以进行双向绑定(bind)

javascript - 更新 Controller 变量更改指令创建的元素

javascript 和 extJs - 范围问题

c# - 如何使用 Javascript 解密

javascript - 在Rails中,我可以在JS响应后在 Controller 操作中执行ActionMailer逻辑吗?

javascript - 加载 Google Client api gapi 和 angular js 的正确顺序

javascript - 无法在 AngularJS 中实例化模块

javascript - 在维护数据的同时链接 promise (angular js)