2

I am trying to minify my js files in my angular app. I know there is some pbs when it comes to dependency injection and minification but I felt like I followed the best practices I found on the internet.

Here is the structure of my code:

My provider:

function myPvdr() {
  this.getUrl = function() {
    return 'http://some/api/call';
  };
  this.$get = function($q, $http) {
    var self = this;
    return {
      getData: function(points) {
        var d = $q.defer();
        $http({
          method: 'GET',
          url: self.getUrl(),
          cache: true
        }).success(function(data) {
          d.resolve(data);
        }).error(function(err) {
          d.reject(err);
        });
        return d.promise;
      }
    }
  }
}

My Controller:

function myCtrl($scope, MyProvider, localStorageService) {
     // some code
}

My Module:

angular.module('myApp', ['LocalStorageModule', 'ngAnimate'])
  .provider('MyProvider', myPvdr)

  // Loading controllers into the module
  .controller('myCtrl', ['$scope', 'MyProvider', 'localStorageService', myCtrl])

It works fine when unminified. But after using the uglify task from grunt I get the following error printed to the console:

Error: [$injector:unpr] http://errors.angularjs.org/1.3.0-rc.2/$injector/unpr?p0=aProvider%20%3C-%20a%20%3C-%20MyProvider

What am I doing wrong?

Spearfisher
  • 8,445
  • 19
  • 70
  • 124

2 Answers2

3

You aren't making your code minfication safe:

There are two options, $injecting or adding it inline when you are declaring the function and using an array with quoted params (things in quotes aren't minified)

https://docs.angularjs.org/tutorial/step_05

Create a $inject property on the controller function which holds an array of strings. Each string in the array is the name of the service to inject for the corresponding parameter. In our example we would write:

function PhoneListCtrl($scope, $http) {...}
PhoneListCtrl.$inject = ['$scope', '$http'];
phonecatApp.controller('PhoneListCtrl', PhoneListCtrl);

Use an inline annotation where, instead of just providing the function, you provide an array. This array contains a list of the service names, followed by the function itself.

function PhoneListCtrl($scope, $http) {...}
phonecatApp.controller('PhoneListCtrl', ['$scope', '$http', PhoneListCtrl]);
John
  • 6,503
  • 3
  • 37
  • 58
  • I've tried both of these methods with the latest angular and the minification looks correct but I still get the error – JJ_Coder4Hire May 25 '17 at 08:32
  • @JJ_Coder4Hire I'd ask a new quesiton and state which version of Angular you are using (original, 2, etc). This is a pretty old solution which was for angular 1 – John May 25 '17 at 15:28
1

If you're already using grunt, consider using the grunt-ng-annotate task. ng-annotate is a tool that automatically inserts proper minification ready syntax where it is needed.