Angular:使用指令时理解DI数组

时间:2014-02-09 11:44:40

标签: javascript arrays angularjs

在尝试决定使用哪种约定(链接与使用var)时,我注意到了

//this works
angular.module("myApp", []);
angular.module('myApp', ['myApp.myD', 'myApp.myD1']);

//while this does not work
var app = angular.module("myApp", ['myApp.myD', 'myApp.myD1']);//fails
var app = angular.module("myApp", []);//must use empty DI

所以我认为(错误的)必须有办法做到这一点:

angular.module("myApp", []);
var myDs=new Array('myApp.myD', 'myApp.myD1');
angular.module('myApp', [myDs]);

随着我的指令列表的增长,我该如何最好地组织和管理它们? 给出一个指令列表:myD,myD1..myDn,我该怎么做 包括一个表示DI中所有指令的数组 阵列

Fiddle1: As var Fiddle2: As chained modules

More: Embrace Conventions..they matter

编辑: 切割并粘贴角形种子

文件一:

angular.module('myApp', [
   'ngRoute',
   'myApp.filters',
   'myApp.services',
   'myApp.directives',
   'myApp.controllers'
])......

文件二:

   angular.module('myApp.directives', []).
       directive('appVersion', ['version', function(version) {
       return function(scope, elm, attrs) {
           elm.text(version);
       };
   }]);

@Baba:非常熟悉种子和引文谢谢。注意角度种子只有一个指令,而Josh的种子据我所见,没有指令。我的目的不是进入最佳实践辩论,而是要了解myApp.directives是在某处定义的数组还是只是依赖数组的名称?我是否将每个指令放在自己的文件中或将所有指令放在文件2下?

2 个答案:

答案 0 :(得分:0)

我经常在一个相当大规模的项目中使用Angular。我们采用了通过链接定义模块而不定义全局变量的约定。这有利于不在闭包上定义全局对象,这些对象可能与其他对象名称重叠并产生奇怪的错误。

你有Angular模块结构,使用它。使用其他方法没有任何实际好处。

至于你的第二个问题,关于组织你的模块,你可能知道组织角度模块有两种主要的方法,即角度种子和角度样板:

https://github.com/angular/angular-seed

http://joshdmiller.github.io/ng-boilerplate/#/home

在大型应用程序中,我认为样板文件是组织模块的更好方法。您还可以查看此博客:

http://www.artandlogic.com/blog/2013/05/ive-been-doing-it-wrong-part-1-of-3/

答案 1 :(得分:0)

由于m.e.conroys的回复,我发现这个问题至少有一个有效的答案。因此,每个依赖项列表显然都使用自己的名称声明并插入到Dependency数组中。

在寻找可扩展的解决方案方面,每个“东西”的一个文件将为大多数项目带来很多痛苦。还要注意m.e. conroy状态“在一个文件中声明一个全局变量,并期望在另一个文件中随时可用,但是不起作用或者可能产生意外结果。”所以Baba不再为我声明var。 Excellent post. Deserves a lot more attention

// My Main Application File
angular.module('myApp',['myDirectives']);

// My Directives File
angular.module('myDirectives',[]);

// Directive One File
angular.module('myDirectives').directive('myD', function () {
    return {
        template: 'Similar to ng-include: tag will not work as element'
    };
});

//Directive Two File
angular.module('myDirectives').directive('myD1', function () {
    return {
        template: 'Similar to ng-include: tag will not work as element'
    };
});