3

我有两个指令,我想在其中一个中公开一个 API 供其他人使用。按照此示例的指导,当我需要其他指令的控制器时,我会收到此错误:

Error: No controller: foo
    at Error (<anonymous>)
    at getControllers (http://localhost:3000/vendor/angular/angular.js:4216:19)
    at nodeLinkFn (http://localhost:3000/vendor/angular/angular.js:4345:35)
    at compositeLinkFn (http://localhost:3000/vendor/angular/angular.js:3953:15)
    at publicLinkFn (http://localhost:3000/vendor/angular/angular.js:3858:30)
    at <error: illegal access>
    at Object.Scope.$broadcast (http://localhost:3000/vendor/angular/angular.js:8243:28)
    at http://localhost:3000/vendor/angular/angular.js:7399:26
    at wrappedCallback (http://localhost:3000/vendor/angular/angular.js:6780:59)
    at wrappedCallback (http://localhost:3000/vendor/angular/angular.js:6780:59) <bar class="ng-scope"> 

我的指令定义如下:

})
    .directive('foo', function() {
        return {
            restrict: 'E',
            template: '<h1>Foo</h1>',
            controller: function($scope) {
                $scope.someArray = [];

                this.doStuff = function() {
                   $scope.someArray.push('abc');
                }
            },
            link: function(scope, element, attrs) {

            }
        }
    })
    .directive('bar', function() {
        return {
            require: 'foo',
            restrict:'E',
            template: '<h1>Bar</h1>',
            link: function(scope, element, attrs, fooCtrl) {
                element.bind('mouseent', function() {
                    fooCtrl.doStuff();
                })
            }
        }
    })

有谁知道为什么第二个指令看不到第一个指令的控制器?

谢谢,

4

1 回答 1

4

require指令定义对象中的属性将控制器注入链接函数。

但是:该指令不会自行启动,您还需要foo在元素中声明该指令。喜欢:<div foo="hello" bar="world"></div>

此外,它有 2 个可以组合的前缀。

  1. ?:“使要求可选”,不会引发错误。
  2. ^:“在父元素中查找它”,通常所需的指令 iw 预计会在同一个元素中。这使它在父元素中搜索。
于 2013-03-31T00:02:52.353 回答