最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Reusing directives for multiple modules - Stack Overflow

programmeradmin6浏览0评论

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 badges
Add a ment  | 

2 Answers 2

Reset to default 6

You 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:

  1. In angularJS, everything is a module. For example, MainApp, OtherApp and even the autoselect directive is a module.
  2. 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

发布评论

评论列表(0)

  1. 暂无评论