递归访问父指令的控制器AngularJS [英] Accessing parent directive's controller recursively in AngularJS

查看:103
本文介绍了递归访问父指令的控制器AngularJS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要得到父母的控制,所以我的指令有需要属性,如下所示:

I need to get parent's controller, so my directive has a require property, as follows:

module.directive('tag', function () {
    return {
        require: '?^tag',
        restrict: 'E',
        controller: function () {
            this.payload = getPayload();
        },
        link: function (scope, element, attrs, ctrl) {
            usePayload(ctrl.payload);
        }
    };
});

然而,链接功能的参数CTRL返回当前的指令,而不是父母的一个控制器。 AngularJS文档清楚这一点:

However the ctrl parameter of the link function returns the controller of the current directive, not the parent's one. AngularJS documentation is clear about this:

^ - ?尝试通过搜索元素的父母找到所需要的控制器,或者如果没有找到返回null

?^ - Attempt to locate the required controller by searching the element's parents, or return null if not found.

我在做什么错了?

推荐答案

无论是文档或code误导这里... 要求 ^ 着眼于当前的元素,然后所有的父,使用 inheritedData 方法(请参阅https://github.com/angular/angular.js/blob/master/src/ng/compile.js#L942).所以,你将不能够要求从使用这种方法父同名的指令。

Either the docs or the code are misleading here... require with ^ looks at the current element and then all parent, using the inheritedData method (see https://github.com/angular/angular.js/blob/master/src/ng/compile.js#L942). So you won't be able to require a directive with the same name from a parent using this approach.

当我已经在过去的这个问题,我看了格式指令,它需要做你的要求。它的控制器方法抓住像这样的父(<一个href=\"https://github.com/angular/angular.js/blob/master/src/ng/directive/form.js#L39\">https://github.com/angular/angular.js/blob/master/src/ng/directive/form.js#L39):

When I've had this issue in the past I've looked at the form directive which needs to do what you are asking. Its controller method grabs the parent like so (https://github.com/angular/angular.js/blob/master/src/ng/directive/form.js#L39):

controller: function($element) {
    var parentForm = $element.parent().controller('form');
}

有鉴于此,你应该能够调用 element.parent()。控制器('标签')发现无论是在控制器或postLink方法父控制器。

Taking this, you should be able to call element.parent().controller('tag') to find the parent controller either in the controller or postLink methods.

这篇关于递归访问父指令的控制器AngularJS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆