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?

Mehdi Dehghani
  • 10,970
  • 6
  • 59
  • 64
Elly Chia
  • 21
  • 6
  • 1) Because it wouldn't work if minified. See https://docs.angularjs.org/guide/di. 2) It's a good idea so as not to [pollute the global namespace](http://stackoverflow.com/questions/8862665/what-does-it-mean-global-namespace-would-be-polluted) with the `Contact` symbol – Phil Aug 29 '16 at 03:49

1 Answers1

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

Jahongir Rahmonov
  • 13,083
  • 10
  • 47
  • 91