简体   繁体   English

使用angular.module的angularjs指令定义

[英]angularjs directive definition using angular.module

Please can anyone explain why the following throws an "Argument 'MainCtrl' is not a function, got undefined" error which seems to be tied into the use of module dependency injection with directives(?!). 请任何人可以解释为什么以下内容引发“ Argument'MainCtrl'不是一个函数,未定义”错误,该错误似乎与使用带指令的模块依赖注入有关。(?!)。

angular.module('app', [])
  .controller('MainCtrl', [function() {
    var self = this;
    self.name = "will this work";
    self.items = [
      {
        name: "name 1",
        test: "test 1"
      },
      {
        name: "name 2",
        test: "test 2"
      }
    ];
  }]);

angular.module('app',[])
  .directive('typeahead', [function() {
    return {
      templateUrl: 'type-ahead.html',
      restrict: 'AEC',
      scope: {
        items: '=',
        prompt: '@',
        title: '@',
        subtitle: '@',
        model: '=',
        onSelect: '&'
      }, <...more code>

Yet it will work perfectly fine when I remove the 但是,当我移除

[ ] []

module dependency braces from the directive to read 模块依赖括号从指令读取

angular.module('app').directive('typeahead', ...) angular.module('app')。directive('typeahead',...)

It also works perfectly fine if I define the directive as a cascade following the controller definition ie 如果我将指令定义为遵循控制器定义的级联,则它也可以很好地工作,即

angular.module('app', [])
      .controller('MainCtrl', [function() {
        var self = this;
        self.name = "will this work";
        self.items = [
          {
            name: "name 1",
            test: "test 1"
          },
          {
            name: "name 2",
            test: "test 2"
          }
        ];
      }])

    .directive('typeahead', [function() {
        return {

Thanks in advance! 提前致谢!

You are running into Angular's Creation versus Retrieval Problem: 您遇到了Angular的创建与检索问题:

Beware that using angular.module('myModule', []) will create the module myModule and overwrite any existing module named myModule. 请注意,使用angular.module('myModule',[])将创建模块myModule并覆盖任何名为myModule的现有模块。 Use angular.module('myModule') to retrieve an existing module. 使用angular.module('myModule')检索现有模块。

The first time you run angular.module('app',[]) , Angular will create a module called app . 首次运行angular.module('app',[]) ,Angular将创建一个名为app的模块。 Next time, you only need to run angular.module('app') , Angular will try to load the existing module app . 下次,您只需要运行angular.module('app') ,Angular将尝试加载现有的模块app

Since you call angular.module('app',[]) once again, module app has been re-initialized. 由于您再次调用angular.module('app',[]) ,因此模块app已重新初始化。 That's why MainCtrl is undefined now. 这就是为什么现在不定义MainCtrl的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM