Best way to perform Dependency injection in Angular JS [closed]

2

I'm working on a fairly large system where I'm building several modules and I needed to be coherent. I'm currently centralizing the dependency injection into a single module, which I believe is not the correct one, since the idea of a module is to be interdependent. Would you have any idea how I can guide you correctly?

    
asked by anonymous 18.01.2016 / 16:43

2 answers

2

I often separate my modules by features, in each feature I place their dependencies and after that I put the feature as dependency of the main module. One suggestion is to take a look at John Paul's styleguide:

link

This specific item talks a bit about dependencies.

    
18.01.2016 / 16:52
2

What I usually do, since they are modules, ie I will use a module only in a certain area of my application, is to use the module ocLazyLoad . It provides loading of my modules (or whatever modules I deem necessary) only in the view (or state) that interests me.

Pros:

  • Application is lighter, since the module is only loaded in a certain view.
  • Security, for the same reason as above. It is only loaded if the user accesses the view.

Cons:

  • If it is a small or complex application, you can increase the work even more, instead of helping.
  • You need to have a better organized control or maintenance, or it may get lost in the code.

The module's site has excellent documentation, but I'll explain how I use it. As I use ui-router in my projects, I apply the oc.lazyload directly to the resolve within the state settings, like this:

.state('inicio', {
    url:'/BemVindo',
    resolve: {
        loadMyCtrl: ['$ocLazyLoad', function($ocLazyLoad) {
            return $ocLazyLoad.load({
                names: 'meuModulo',
                files: 'app/modulo/meumodulo.js'
            });
        }]
    }
})

Note that using this tool you will no longer need to declare the module meuModulo (for example) in your main module:

angular.module('mainApp', [
    'meuModulo' //Não é mais necessário isso
]);

The oc.lazyload tool will be responsible for loading both the physical file (meumodulo.js) and the dynamic injection of the module for use. The good thing about this tool is also the 'no' dependency of doing the load only on the router. There are other ways to do this, for example, through a directive:

<div oc-lazy-load="['meumodulo.js']">
    //.. restante do conteudo
</div>

Note: oc.lazyload is not the only method of getting this result, there are other tools that can also do this, such as RequireJs . This is just my method to use.

Just look at the naming of your modules, do not use something too short, like mdNot , use something more intuitive like mdNoticias .

Other tips better, follow the link provided in the other answer. The John guide is really a great source!

    
18.01.2016 / 19:41