How to share a single Directive across multiple modules in AngularJS

后端 未结 3 1460
[愿得一人]
[愿得一人] 2021-01-30 22:11

As far as I know about AngularJS, this is one of the interesting libraries out today. I am slowly understanding the Angular power, and I am seriously loving it. I have a few dou

3条回答
  •  萌比男神i
    2021-01-30 23:02

    Q: For example I have a module in my App and I have directives written for it, And I want to add few more modules to my app and also want to reuse existing directives written for another module. How I can achieve that. Not only modules that applies to filters, config etc..

    When you declare a module, you specify its dependencies. So if you have a directive like this:

    angular.module( 'moduleA', [] )
    
    .directive( 'myDirective', function () {
      // ...
    });
    

    You can require that module from another module:

    angular.module( 'moduleB', [ 'moduleA' ] );
    

    The array argument to angular.module is a list of dependencies.

    Q: Can I have sub modules defined inside a Module?

    Modules are technically all independent, but it's super common to fake it. So we can define moduleA with it's "submodules" like so:

    angular.module( 'moduleA.one', [] );
    angular.module( 'moduleA.two', [] );
    
    angular.module( 'moduleA', [
      'moduleA.one',
      'moduleA.two'
    ]);
    

    And it's clear to the developer/reader that moduleA.one and moduleA.two are part of moduleA, but also anytime another module depends on moduleA, its two submodules will be included as well.

    But technically, these are all independent, so moduleB could also require moduleA.two if it wanted to do so.

    Q: How can I add a controller to an element dynamically, it should not be static, i.e through html markup ng-controller.

    This is probably not a good idea. The "view" is the official record. What's your use case?

    Q: If I want to share a thing across all modules how can I do that.. For example I have a variable defined outside of all modules in my app and I just want to access them inside modules.. Is that possible, I have this doubt because it completely works on individual scopes, shared scope and rootScope etc..

    I am not sure I understand what you're asking. But when you define something in a module, you can access it from any other just by requiring it, as discussed above. But in an AngularJS app, there should be anything "outside of all modules" - everything should be in a module because otherwise it'ts defined in the global scope (e.g. window) and that's just bad practice.


    To get a better understanding of how modules can be structured to great benefit, check out my ngBoilerplate kickstarter: http://ngbp.github.io/ngbp/. The module structure is specifically designed for code reuse and demonstrates many of these concepts in practice.

    Feel free to elaborate on any of these and I will revise the responses.

提交回复
热议问题