When adding AngularJS to your ASP.NET MVC project that also takes advantage of bundling you may be in for a surprise when you deploy to your production site. Your AngularJS code will no longer work! A quick check of your favorite debugging console will show an error similar to this one:
Uncaught Error: [$injector:modulerr] Failed to instantiate module myApp due to: Error: [$injector:unpr] Unknown provider: n
The reason for this is due to your AngularJS code being minified and the parameter names that AngularJS rely on for dependency injection have been changed. Fortunately there is a way to min-safe your code and still take advantage of ASP.NET Web Optimization.
Typically when defining modules and using the inline functions when defining controllers like so:
var myApp = angular.module("myApp", []); myApp.controller("controller1", function ($scope, $http, $log) {…});
You replace the inline function with a inline bracket notation that passes an array of strings that represents the parameter names to be injected into the function. So the above sample code is now:
var myApp = angular.module("myApp", []); myApp.controller("controller1", ["$scope", "$http", "$log", function ($scope, $http, $log) {…}]);
If you are not using an inline function but rather passing the name of a function the same bracket notation works as well. Also this notation will also be needed when defining services or any other AngularJS construct that will be relying on dependency injection.
There are other solutions to this problem like using the $inject property and passing the array of strings for dependency names. Personally I found this method more clunky, but check out the AngularJS documentation for more detail if you’re interested.
If you are using inline functions you can check out “ngmin”. This is a pre-minifier that will modify your code to make it min-safe. This requires using Node.js and again personally I found this be rather clunky when working in ASP.NET. Manually making the changes is just a little more work, but worth it.
Leave a Reply
You must be logged in to post a comment.