【问题标题】:AngularJS Two directives with the same module nameAngularJS 两个具有相同模块名称的指令
【发布时间】:2013-12-03 08:15:00
【问题描述】:

是否可以创建两个具有相同模块名称的指令? 拥有这两个文件

angular.module('fabTemplate', [])
    .directive('fabGallery', [function () {
....

angular.module('fabTemplate', [])
    .directive('fabVideo', [function () {
...

第二个指令将不会被识别。

<fab-video />

不渲染任何东西。通过更改模块名称虽然有效。

AngularJS 的documentation says 表示参数名称(模块“方法”的第一个参数)

要创建或检索的模块的名称。

我想那应该可以工作......:S Angular 不会在控制台中打印任何内容

【问题讨论】:

    标签: angularjs


    【解决方案1】:

    根据您链接的文档,当您将第二个参数添加到 module 方法时,它明确调用模块的 creation ,而不是 retrieve ;事实上,这个参数是可选的,所以当你只想检索现有模块时,你应该可以这样做:

    angular.module('fabTemplate')
        .directive('fabVideo', [function () {
    

    【讨论】:

      【解决方案2】:

      它也写在文档的开头:

      当传递两个或多个参数时,会创建一个新模块。如果只传递一个参数,则检索现有模块(作为第一个参数传递给模块的名称)。

      如果你想检索模块,你应该在第二次只传递模块名称,而不是数组。

      所以,你应该写:

      angular.module('fabTemplate', [])
          .directive('fabGallery', [function () {
              ....
          }]);
      
      angular.module('fabTemplate')
          .directive('fabVideo', [function () {
              ....
          }]);
      

      注意你可以写:

      angular.module('fabTemplate', [])
          .directive('fabGallery', [function () {
              ....
          }])
          .directive('fabVideo', [function () {
              ....
          }]);
      

      或者

      var fabTemplate = angular.module('fabTemplate', []);
      
      fabTemplate.directive('fabGallery', [function () {
          ....
      }]);
      
      fabTemplate.directive('fabVideo', [function () {
          ....
      }]);
      

      【讨论】:

        【解决方案3】:

        如果你想检索一个模块,那么你必须只使用 angular.module() 的第一个参数。

        From the docs:

        requires (optional) [Array.] :如果指定,则正在创建新模块。如果未指定,则正在检索模块以进行进一步配置。

        你的代码应该是这样的:

        //Module definition:
        angular.module('fabTemplate', []);
        
        //Get the module and add the first directive:
        angular.module('fabTemplate').directive('fabGallery', function () {});
        
        //Get the module and add the second directive:
        angular.module('fabTemplate').directive('fabVideo', function () {});
        

        【讨论】:

          【解决方案4】:

          一个模块中可以有多个指令。

          angular.module('myModule', []).directive('first', function() {
          angular.module('myModule').directive('second', function() {
          

          您必须确保第一个声明中的方括号不在其他声明中。参考这个帖子:AngularJS module.directive not responding consistently

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2014-11-12
            • 2013-07-25
            • 2016-10-01
            • 1970-01-01
            • 1970-01-01
            • 2018-12-21
            • 1970-01-01
            • 2017-02-24
            相关资源
            最近更新 更多