Whi*_*her 100 javascript dependency-injection angularjs
我正在阅读 http://www.alexrothenberg.com/2013/02/11/the-magic-behind-angularjs-dependency-injection.html,结果发现如果你缩小你的javascript,angularjs依赖注入有问题,所以我我想知道是否代替
var MyController = function($scope, $http) {
$http.get('https://api.github.com/repos/angular/angular.js/commits')
.then(function(response) {
$scope.commits = response.data
})
}
Run Code Online (Sandbox Code Playgroud)
你应该使用
var MyController = ['$scope', '$http', function($scope, $http) {
$http.get('https://api.github.com/repos/angular/angular.js/commits')
.then(function(response) {
$scope.commits = response.data
})
}]
Run Code Online (Sandbox Code Playgroud)
总而言之,我认为第二个片段是旧版本的angularjs,但....
我应该总是使用注入方式(第二个)吗?
Sel*_*lai 100
是的,总是!所以这种方式即使你的minifer将$ scope转换为变量a和$ http转换为变量b,它们的身份仍然保留在字符串中.
请参阅AngularJS文档的此页面,向下滚动到关于缩小的A Note.
UPDATE
或者,您可以在构建过程中使用ng-annotate npm包来避免这种冗长.
只是要指出,如果你使用
没有必要这样做
var MyController = ['$scope', '$http', function($scope, $http) {
$http.get('https://api.github.com/repos/angular/angular.js/commits')
.then(function(response) {
$scope.commits = response.data
})
}]
Run Code Online (Sandbox Code Playgroud)
因为minify期间的grunt考虑了如何管理DI.
是的,您需要使用显式依赖注入(第二个变体).但是从Angular 1.3.1开始,你可以关闭隐式依赖注入,这对于解决立即重命名(缩小之前)的潜在问题非常有帮助.
使用strictDiconfig属性关闭隐式DI :
angular.bootstrap(document, ['myApp'], {
strictDi: true
});
Run Code Online (Sandbox Code Playgroud)
关闭隐式DI,使用ng-strict-di指令:
<html ng-app="myApp" ng-strict-di>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
94883 次 |
| 最近记录: |