Che*_*hev 6 javascript dependency-injection angularjs angularjs-directive
考虑Brad Green的AngularJS的这个片段.
var directives = angular.module('guthub.directives', []);
directives.directive('butterbar', ['$rootScope',
function ($rootScope) {
return {
link: function (scope, element, attrs) {
element.addClass('hide');
$rootScope.$on('$routeChangeStart', function () {
element.removeClass('hide');
});
$rootScope.$on('$routeChangeSuccess', function () {
element.addClass('hide');
});
}
};
}]
);
directives.directive('focus', function () {
return {
link: function (scope, element, attrs) {
element[0].focus();
}
};
});
Run Code Online (Sandbox Code Playgroud)
请注意,对于"butterbar"指令,他传入一个数组,其中第一项只是具有依赖项名称的字符串,"$rootScope"第二项是函数.该函数声明了依赖$rootScope.为什么我们在这里重复一遍?特别是当它似乎可以这样做时:
directives.directive('butterbar', function ($rootScope) {
return {
link: function (scope, element, attrs) {
element.addClass('hide');
$rootScope.$on('$routeChangeStart', function () {
element.removeClass('hide');
});
$rootScope.$on('$routeChangeSuccess', function () {
element.addClass('hide');
});
}
};
});
Run Code Online (Sandbox Code Playgroud)
我猜测依赖名称是一个字符串具有某种意义.任何人都可以告诉我为什么他们在整本书中这样做(而不仅仅是指令)?
iCo*_*nor 13
当JavaScript被缩小时,参数的名称通常会更改为更短的内容,例如a.这会打破依赖注入.
如果你使用数组,Angular知道要注入什么以及注入它的位置.这适用于数组,因为数组的字符串元素不会被缩小修改.
在这个例子中:
app.controller('test', function( $scope, $someProvider ) {
});
Run Code Online (Sandbox Code Playgroud)
缩小的代码可能看起来像这样:
app.controller('test',function(a,b){});
Run Code Online (Sandbox Code Playgroud)
这将不再有效,因为Angular不知道要注射什么,而这样:
app.controller('test', ['$scope', '$someProvider', function( $scope, $someProvider) {
}]);
Run Code Online (Sandbox Code Playgroud)
缩小的代码可能会像这样结束:
app.controller('test',['$scope','$someProvider',function(a,b) {}]);
Run Code Online (Sandbox Code Playgroud)
这仍然有效,因为Angular仍然知道要注入什么.请参阅Angular教程中关于缩小的注释.
通常我只是在准备生产时添加数组样式.
| 归档时间: |
|
| 查看次数: |
465 次 |
| 最近记录: |