Best Way to Perform Dependency Injection on Angular JS

Asked

Viewed 1,104 times

2

I am working on a very large system where I am creating several modules and needed to guide them in a coherent way. Currently I am centralizing the injection of dependency in a single module, what I believe is not the correct one, because the idea of module is to be interindependente. Would you have any idea how I can guide you properly?

2 answers

2


I usually separate my modules by Features, in each Feature I put their dependencies and after that I put Feature as dependency of the main module. A suggestion is to take a look at the styleguide of Jhon Papa:

https://github.com/johnpapa/angular-styleguide#style-y165

This particular item talks a little bit about dependencies.

2

What I usually do, since they are modules, that is, 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 modules I think necessary) only in the view (or state) that interests me.

Pros:

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

Cons:

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

The site of the module has excellent documentation, but I will explain how I use. How I use ui-router in my projects, I apply the use of oc.lazyload directly on resolve within the settings of state, thus:

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

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

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

The tool oc.lazyload will take care of both the loading of 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 to load only on the router. There are other ways to do this, such as through a Directive:

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

Note: The oc.lazyload is not the only method of getting this result, there are other tools that can also do this, as Requirejs. This is just my method of using.

Just keep in mind the nomenclature of your modules, don’t use something too brief, like mdNot, use something more intuitive like mdNoticias.

Other better tips, follow the link provided in the other answer. The guide to John is really an excellent source!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.