Prashant Sharma Prashant Sharma - 1 year ago 80
AngularJS Question

use of $inject in angular js in controllers?

I am new to angularjs , I am totally confused about inject. I do not know where to use it and why? Is this only use with factory as explain in this link inject link?

myController.$inject = ['$scope','notify'];

Here,notify is name of the factory.

Answer Source

That is one approach to support Dependency Injection after your code is minified (if you choose to minify).

When you declare a controller, the function takes parameters:

function ($scope, notify)

When you minify the code, your function will look like this:

function (a, b)

Since AngularJS uses the function parameter names to infer DI, your code will break because AngularJS doesn't know about a or b.

To solve this problem, they provided additional ways to declare controllers (or other services/factories/etc) for that matter:

1) For controllers, use the $inject method - here you pass an array of literals that map to the parameters of your controller function. So, if you provide

['$scope', 'notify']

then the value of the first parameter to your function will be the a scope object associated with this controller and the second parameter will be the notify service.

2) When declaring new controllers, services, etc, you can use the array literal syntax. Here, you do something like this:

    angular.module('myModule').controller('MyController', ['$scope', 'notify', function ($scope, notify) {

The array as a parameter to the controller function maps the DI objects to your function parameters.

I prefer Option #2 when declaring controllers etc as it is easier to read/understand/cross-check since it is all in the same place.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download