javascript - I don't understand the use of $inject in controllers -
i totally confused inject in angular. not know use , why. used factory described here?
mycontroller.$inject = ['$scope','notify'];
here notify
name of factory.
that 1 approach support dependency injection after code minified (if choose minify).
when declare controller, function takes parameters:
function ($scope, notify)
when minify code, function this:
function (a, b)
since angularjs uses function parameter names infer di, code break because angularjs doesn't know a
or b
.
to solve problem, provided additional ways declare controllers (or other services/factories/etc) matter:
for controllers, use
$inject
method - here pass array of literals map parameters of controller function. so, if provide['$scope', 'notify']
then value of first parameter function scope object associated controller , second parameter notify service.
when declaring new controllers, services, etc, can use array literal syntax. here, this:
angular.module('mymodule').controller('mycontroller', ['$scope', 'notify', function ($scope, notify) { ... }]);
the array parameter controller function maps di objects function parameters.
i prefer option #2 when declaring controllers etc easier read/understand/cross-check since in same place.
Comments
Post a Comment