Reusing directives for multiple modules

I would like to know how best to use the same directive for multiple modules. In my opinion, I believe that directives are similar to DOM modules, so the angular architecture for this is a little annoying to my point of view.

Now I do this:

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

var otherapp = angular.module('OtherApp');
otherapp.controller( ... );

And in another file, I have my directive that I want to use in these two controllers / modules

mainapp.directive('autoselect', function(){ ... });

But, as you can see, I have to indicate in which application I should use it. If I want to use in both cases, do I need to copy the same code twice?

+4
source share
2 answers

, (, , , ..) .

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

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

var otherapp = angular.module('OtherApp', ['CommonApp']);
otherapp.controller( ... );
+6

, , / .

:

  • angularJS . , MainApp, OtherApp autoselect .
  • "" .

, :

angular.module('com.example.mydirective', [])
  .directive('autoselect', function() { ... });

angular.module('MainApp', ['com.example.mydirective']);
  .controller(...);

angular.module('OtherApp', ['com.example.mydirective']);
  .controller(...);

, : , , .

angular.module('module-name', []); // this line tells angularJS to create a new module

angular.module('module-name'); // no brackets -- this asks angularjs to return a pre-existing module

,

+4

All Articles