且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我们在angularjs中注入我们的依赖关系两次?

更新时间:2023-01-11 09:38:23

这是为了使应用程序安全。


小心:如果您计划最小化代码,您的依赖名称将被重命名并破坏您的应用程序。


当您将(或可能)缩小所有文件时,依赖关系将替换为 a b ,...等。



但是,当您使用数组和字符串如语法时,如第二个所示片段, string 永远不会细化,可用于映射。所以,应用程序知道 a $ scope (见下面的示例)。



示例:

  //最小化的版本
var _ = angular.module(' analysisApp',[]);

_.controller('analysisController',['$ scope','$ http','$ cookies','$ state','globalService',function(a,b,c,d ,e){
a.name ='John Doe'; //现在这里是`$ scope`
}]);

请参阅角度文件



这是很好的文章。



为了最小化***做法:Angularjs最优化实践


I'm new in angular, want to know why and when we should inject all our needed dependencies two times.

Example :

var analysisApp=angular.module('analysisApp',[]);

analysisApp.controller('analysisController',function($scope,$http,$cookies,$state,globalService){   

});

But we can also write the above code as :

var analysisApp=angular.module('analysisApp',[]);

analysisApp.controller('analysisController',['$scope','$http','$cookies','$state','globalService',function($scope,$http,$cookies,$state,globalService){ 

}]);

Why ?

This is to make the app minsafe.

Careful: If you plan to minify your code, your dependency names will get renamed and break your app.

When you will(or may), minify all the files, the dependencies are replaced by the words like a, b, ... etc.

But, when you use array and string like syntax, as shown in the second snippet, the string are never minifies and can be used for mapping. So, the app knows that a is $scope(See below example).

Example:

// The minified version
var _ = angular.module('analysisApp', []);

_.controller('analysisController', ['$scope', '$http', '$cookies', '$state', 'globalService', function (a, b, c, d, e) {
    a.name = 'John Doe'; // Now a here is `$scope`.
}]);

See Angular Docs

Here is nice article for making your app minsafe with Grunt.

For minification best practices: Angularjs minify best practice