通过Angular require属性访问父级的父控制器

时间:2013-02-18 12:05:58

标签: angularjs angularjs-directive

在下面的示例中,accordion-group指令使用accordion-group指令中的“require:'^ accordion'”属性与父手风琴共享控制器和范围。

如果我想创建一个子指令,在accordion-group下,它如何访问手风琴控制器呢?要求^ accordion和^ accordionGroup似乎不起作用。

https://github.com/angular-ui/bootstrap/blob/master/src/accordion/accordion.js

1 个答案:

答案 0 :(得分:1)

它确实有效。我只是傻了。 后人的小提琴here

'use strict';

angular.module('myApp', []).controller('OneController', function() {
    this.test = function(element) {
        element.css('color', 'red');
    }
}).directive('one', function() {
    return {
        restrict: 'E',
        transclude: true,
        replace: true,
        controller: 'OneController', 
        template: '<span ng-transclude>And a </span>',
    }
}).directive('two', function() {
    return {
        restrict: 'E',
        transclude: true,
        replace: true,
        require: '^one',
        template: '<span ng-transclude>and a </span>',
    }
}).directive('three', function() {
    return {
        restrict: 'E',
        transclude: true,
        replace: true,
        require: '^one',
        template: '<span ng-transclude>and a one two</span>',
        link: function(scope, element, attrs, ctrl) {
            ctrl.test(element);
        }
    }
});