chrony
chrony

Reputation: 783

Advantage of using $injector vs explicit DI declaration AngularJS

Just wondering if there's difference between:

angular.module('app', [])
.controller('myctrl', ['$scope', 'customService',
     function($scope, customService) {
         // use customService
     }
]);

and using $injector

angular.module('app', [])
.controller('myctrl', ['$scope', '$injector',
     function($scope, $injector) {
         // get customService via injector and use it
         $injector.get('customService');
     }
]);

Sometimes I need to inject quite a few dependencies and my parameter list ends up to be lengthy. That's why I'm thinking the latter approach may be better for my scenario.

Does the difference affect testing or minification or any other reason?

Upvotes: 0

Views: 110

Answers (2)

Omri Aharon
Omri Aharon

Reputation: 17064

Basically there is not much different, until you first encounter your circular dependency error while loading your module.

Simple Fiddle that demonstrates circular dependency.

Code (from fiddle):

angular.module('app', [])
.service('serviceA', function (serviceB) {
    return {};
})
.service('serviceB', function (serviceA) {
    return {};
})
.controller('myCtrl', function (serviceA, serviceB) {
});

Using $injector helps prevent that scenario because when you use it inside the Controller/Factory/Service/etc instead of injecting the first way, you are delaying the dependency and therefore solving the problem.

And a simple Fiddle that demonstrates how that problem is solved.

Code (from fiddle):

angular.module('app', [])
.service('serviceA', function (serviceB) {

    return {
        test: "it works!"
    };
})
.service('serviceB', function ($injector) {


    return {
        test: function() {
            var serviceA = $injector.get("serviceA");   

            return serviceA.test;
        }
    };
})
.controller('myCtrl', function ($scope, serviceA, serviceB) { 
    $scope.test = serviceB.test();
});

Upvotes: 1

technoSpino
technoSpino

Reputation: 510

You are on the right track. Look at John Papa's Style Guide. You will do the injection before the controller function.

/* recommended */
angular
    .module('app')
    .controller('Dashboard', Dashboard);

Dashboard.$inject = ['$location', '$routeParams', 'common', 'dataservice'];

function Dashboard($location, $routeParams, common, dataservice) {
}

Upvotes: 1

Related Questions