angularjs - 错误 : No controller

标签 angularjs

我有两个指令,我想在其中一个指令中公开 API 以供其他人使用。遵循 this example 的指导当我需要其他指令的 Controller 时出现此错误:

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

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

谢谢,

最佳答案

require指令定义对象中的属性将 Controller 注入(inject)链接函数。

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

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

  1. ? : "Make requirement optional", 没有出现错误。
  2. ^ :“在父元素中查找”,通常所需的指令 iw 预计在同一元素中。这使得它在父元素中搜索。

关于angularjs - 错误 : No controller,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15724168/

相关文章:

angularjs - 我想动态应用 ui 路由器中的参数

angularjs - 以编程方式控制 Angular-ui Accordion 的好方法是什么?

javascript - 在 AngularJS 中不使用 JQuery 获取多个元素的高度

javascript - 为什么 $rootScope 绑定(bind)有效,但在子 Controller 中调用 $parent 却不起作用?

angularjs - 尽管存在 Set-cookie header ,但 Laravel Cookie 未设置

javascript - 动态更改 Angular Directive(指令)中的模板

javascript - 如何使用 HTML5、JS 或 Angular 验证 Ionic 中的电子邮件?

javascript - 当用户在输入文本中键入逗号时,Angularjs 会观察

javascript - AngularJS Controller 缓存在 Firefox 和 IE : how to disable?

java - Spring 拦截不起作用