1
(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?

1

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.