0
var myapp=angular.module('myAppln',[]);

I am new to angularjs. Why should we use [] in angular.module()? Could anybody please explain.

Alexandr Lazarev
  • 12,554
  • 4
  • 38
  • 47
NageswaraRao .K
  • 53
  • 1
  • 1
  • 8
  • 3
    possible duplicate of [What is the meaning of the square brackets in “.module("modulename", \[…\])” of AngularJS](http://stackoverflow.com/questions/31989675/what-is-the-meaning-of-the-square-brackets-in-modulemodulename-of-an) – LionC Sep 24 '15 at 10:00
  • 1
    `[]` in JS means that it's an Array. It's not unique to AngularJS. Angular's `module()` accepts 2 params - a module name and list of dependency modules. When we say `angular.module('myAppln',[]);`, you're create a new Angular module called `myAppln` and it has no dependencies on any other Angular modules. If you need some other Angular module like angular-resource or angular-router, then we say `angular.module('myApp',['ngRoute','ngResource']);` – Arkantos Sep 24 '15 at 10:06

3 Answers3

2

This is used for injecting dependency. Dependency Injection or DI is a software design pattern in which components are given their dependency instead of hard coding them within the component. This is also helpful in making dependency configurable and make components resuable & maintainable.

Components such as services & directives are defined using injectable factory For example when define a service in angularjs we do like this way

var abc = angular.module('ngAppName',[]);
    abc.factory('serviceName',['$http',function($http){
    // Rest of code goes here
    }])

angular.module('ngAppName',[]) It is more or less entry point for angular application & here we do not have any dependency so this is an empty array.

But take a look when we are defining our custom service.Here this service has dependency on $http which is predefined service offered by angular for ajax call.Our custom service(serviceName) has dependency on this $http, which we are injecting here

Another example with angular route

abc.config(['$routeProvider',function($routeProvider){
      // Rest of code goes her
    }])

The $routeProvider is what creates the $route service and it is provided by angularjs. While creating route we have to depend on $routeProvider. So we have injected it our code.

Hope this will be helpful for you.

brk
  • 48,835
  • 10
  • 56
  • 78
0

if you go further in Angular.js then you will read that you can pass injectors and other stuff to module. So here api return in a manner that it receaves array of options. when you wont have any you just pass it blank []

Parasmani Batra
  • 207
  • 1
  • 5
0

Actually [] is an array with the dependencies that are required by the module.

Alexandr Lazarev
  • 12,554
  • 4
  • 38
  • 47