今天在把 AngularJS 的 Code 放上 Production 環境時出現了一個問題:


點擊會連到https://docs.angularjs.org/error/injector錯誤,直接展開看minified後的JS發現$scope被轉成a了, 因為minified會透過縮減變數名稱節省檔案大小!

Sample code (wrong) :

1
2
3
4
5
6
7
App.controller("MyCtrl", function ($scope) {  
$scope.foo= "foo";
});

//After Minified:(可透過[線上minified網站](http://refresh-sf.com/)試試看)
App.controller("MyCtrl",function(o){o.foo="foo"});
//Cause Error: [$injector:unpr] https://errors.angularjs.org/1.2.26/$injector/unpr?.....

解決方法:在inject時明確指定inject的物件

1
2
3
4
5
6
7
App.controller("MyCtrl", ["$scope", function ($scope) {  
$scope.foo= "foo";
}]);

//After Minified:
App.controller("MyCtrl",["$scope",function(o){o.foo="foo"}]);
//No error