user2650480
user2650480

Reputation: 479

Angular javascript minification cause Error: $injector:modulerr Module Error

When I define angular like following, it will cause issue on using minification this javascript, which is Error: $injector:modulerr Module Error.

angular.module('myModule').controller('MyController', function ($scope) {

});

Now, if I write my angular as following, it'll be fine after minification.

angular.module('myModule').controller('MyController', ["$scope", function ($scope) {

}]);

During the minification, the first way will convert the $scope to other variable name, looks like that the issue. Is there a way I can avoid not writing code as the second case?

Upvotes: 1

Views: 1378

Answers (3)

Andreas Jägle
Andreas Jägle

Reputation: 12240

If you have some kind of build-process (or you want to introduce a pretty small one), have a look at the ng-annotate project (https://github.com/olov/ng-annotate). It is a tool that processes your javascript code and helps you avoid repeating yourself. What it does is basically reading the first version of your code and generating an $inject property for you as shown in the answer of Pedro Nascimento.

There are several plugins for grunt, gulp, webpack and so on, but it's also pretty easy to just use this one module if you don't have a build process yet.

Upvotes: 1

Steeve Pitis
Steeve Pitis

Reputation: 4443

You have this for Grunt : https://www.npmjs.com/package/grunt-ng-annotate I'm pretty sure you could find the same thing for webpack/gulp etc...

Upvotes: 0

Pedro Nascimento
Pedro Nascimento

Reputation: 13886

You can use $inject:

function MyController($scope) {
}

MyController.$inject = ['$scope'];
angular.module('myModule').controller('MyController', MyController);

Upvotes: 2

Related Questions