Elly Chia
Elly Chia

Reputation: 31

angularjs services using $inject?

(function() {
    angular.module('MyApp')
        .factory('Contact', Contact);

    Contact.$inject = ['$http'];

    function Contact($http) {
        return {
            send: function(data) {
                return $http.post('/contact', data);
            }
        };
    }
})();

In a boilerplate I found above code. I have few confusions :

  1. why not just inject $http like this

    angular.module('MyApp').factory('Contact', function($http){ });

  2. is it necessary to put the service within self-execution function?

Upvotes: 1

Views: 35

Answers (1)

Jahongir Rahmonov
Jahongir Rahmonov

Reputation: 13723

First - The problem will arise when you try to minimize your angular files. Your minimizer may convert $http to variable b and their identity will still be preserved in the strings if you use $inject otherwise you will have errors.

Second - When you are using self-executed functions, you are isolating the scope of your services. That will help when you combine all the files into one. If you don't do that variables or functions with the same name will produce errors.

This is explained in more detail in John Papa's styleguide

Hope it helps

Upvotes: 3

Related Questions