Meaning of the empty array in angularJS module declaration

All we need is an easy explanation of the problem, so here it is.

In my previous question, I understand that the code var app = angular.module('myApp', []); connects the module app to the view myApp.

I would like to know why we are having the empty array [] in the module declaration.

What is the empty array used for?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

angular.module('app', []) is to create a new module without any module dependency.

angular.module('app') is to retrieve an existing module whose name is app.

Method 2

That array is meant to add various module to your current app which
is mentioned in your first part of angular.module as string`, You could simply
say for injecting various dependency.

You could create an n number of module inside your app for each component of angular & then you could combine them into one single app and you can angular.bootstrap or apply it on page using ng-app directive.

Example

Suppose you have an app which has different component like services, factory, filters, directives, etc. You could create a module for each of them. Just for making separation of concern.

angular.module('myApp.filters', [])
angular.module('myApp.services', [])
angular.module('myApp.controllers', [])
angular.module('myApp.directives', [])
angular.module('myApp.constants', [])

And while appending an component to it you could simply use that specific module of it. Like you wanted to add service then you just add that service into myApp.services by doing

angular.module('myApp.services').service('example', function(){

})

And then inside you app.js you could do combine all of this modules to an single module like below.

angular.module('myApp', [
     'myApp.services', 
     'myApp.controllers', 
     'myApp.directives', 
     'myApp.directives', 
     'myApp.constants'
])

While initializing an app you could simply use myApp inside, that would make available all other module to it.

What is the empty array used for?

In you code you are creating an module which doesn’t inject any dependency, [] which means it is independent of any other angular module.

Dependency injected inside the [] is nothing but importing module

Method 3

Angulars API says Passing one argument retrieves an existing angular.Module, whereas passing more than one argument creates a new angular.Module
https://docs.angularjs.org/api/ng/function/angular.module

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply