Sanjay Sutar
Sanjay Sutar

Reputation: 544

injecting dependency through factory in AngularJs

I have below service code

(function () {
    'use strict';

    angular.module('App')
           .factory('apiservice', apiservice);

    /* @ngInject */
    function apiservice($http) {
        var service = {
            getData: getGridData,
        };

        return service;

       //code ommitted for clarity
    }
})();

When I minifying and bundling, the dependency is getting screwed up. So I wanted to change $scope to '$scope' so minifier won't mess up with name.

I know there are several ways to do it. But can I make it work like below:

(function () {
    'use strict';

    angular.module('App')
           .factory('apiservice', ['http', apiservice]);

    function apiservice($http) {
        return service;
    }
})();

Any help is appreciated.

Upvotes: 1

Views: 52

Answers (1)

Dan Prince
Dan Prince

Reputation: 29989

You have a couple of options,. the first is to use the extended syntax for dependency injection. In this case:

.factory('apiservice', ['$http', apiservice]);

function apiservice($http) {
  return service;
}

This can also be written as:

.factory('apiservice', apiservice);

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

function apiservice($http) {
  return service;
}

Or put add another build step before you minify, such as ng-annotate which will convert your syntax to the extended version.

A factory like this

.factory('apiservice', function($http) {
  return service;
});

Would become:

.factory('apiservice', ['$http', function($http) {
  return service;
});

Which would be safe to minify.

Upvotes: 1

Related Questions