4

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

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 文档对此很清楚:

?^ - 尝试通过搜索元素的父元素来定位所需的控制器,如果未找到则返回 null。

我究竟做错了什么?

4

1 回答 1

10

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.

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');
}

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

于 2013-10-11T16:52:52.333 回答