重用多个模块的指令

EnZ*_*nZo 4 javascript angularjs angularjs-directive

我想知道为多个模块重用相同指令的最佳方法是什么.在我看来,我认为指令就像DOM模块,所以角度的架构对我的观点有点烦人.

我现在这样做的方式是:

var mainapp = angular.module('MainApp');
mainapp.controller( ... );

var otherapp = angular.module('OtherApp');
otherapp.controller( ... );
Run Code Online (Sandbox Code Playgroud)

在其他文件中,我有我的指令,我想在这两个控制器/模块中使用

mainapp.directive('autoselect', function(){ ... });
Run Code Online (Sandbox Code Playgroud)

但正如您所看到的,我必须指定在哪个应用程序中使用它.如果我想在两者中使用,我是否必须复制两次相同的代码?

小智 6

您可以维护一个包含公共(服务,指令,值,常量等)的模块并注入每个模块.

angular.module('CommonApp',['OtherCommonModule1','OtherCommonModule2']).directive(..);

var mainapp = angular.module('MainApp', ['CommonApp']);
mainapp.controller( ... );

var otherapp = angular.module('OtherApp', ['CommonApp']);
otherapp.controller( ... );
Run Code Online (Sandbox Code Playgroud)