I would like to know what is the best way to reuse the same directive for multiple modules. In my mind i think directives are like DOM-modules, so the architecture of angular for this is a bit annoying of my point of view.
The way I'm doing it now is:
var mainapp = angular.module('MainApp');
mainapp.controller( ... );
var otherapp = angular.module('OtherApp');
otherapp.controller( ... );
And in other file i have my directive i want to use in this two controllers/modules
mainapp.directive('autoselect', function(){ ... });
But as you can see, I have to specify in what app I have to use it. If I want to use in both, do i have to copy twice the same code?
I would like to know what is the best way to reuse the same directive for multiple modules. In my mind i think directives are like DOM-modules, so the architecture of angular for this is a bit annoying of my point of view.
The way I'm doing it now is:
var mainapp = angular.module('MainApp');
mainapp.controller( ... );
var otherapp = angular.module('OtherApp');
otherapp.controller( ... );
And in other file i have my directive i want to use in this two controllers/modules
mainapp.directive('autoselect', function(){ ... });
But as you can see, I have to specify in what app I have to use it. If I want to use in both, do i have to copy twice the same code?
Share Improve this question asked Nov 4, 2014 at 3:33 EnzoEnzo 4,1915 gold badges24 silver badges35 bronze badges2 Answers
Reset to default 6You can maintain a module that contains mon (services, directives, values, constants etc.) and inject into each module.
angular.module('CommonApp',['OtherCommonModule1','OtherCommonModule2']).directive(..);
var mainapp = angular.module('MainApp', ['CommonApp']);
mainapp.controller( ... );
var otherapp = angular.module('OtherApp', ['CommonApp']);
otherapp.controller( ... );
No, you don't have to specify which app/module you need to use a directive in.
Let me explain:
- In angularJS, everything is a module. For example, MainApp, OtherApp and even the autoselect directive is a module.
- Each module can 'depend' on one or more modules.
So, here's how I would design the solution:
angular.module('.example.mydirective', [])
.directive('autoselect', function() { ... });
angular.module('MainApp', ['.example.mydirective']);
.controller(...);
angular.module('OtherApp', ['.example.mydirective']);
.controller(...);
One thing I'd like to add: the square brackets that denote the dependency have a special significance.
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
Hope this helps