显式和隐式依赖注入
把service当作被依赖的资源加载到controller中的⽅方法,与加载到其他服务中的方法很相似。
javascript是一个动态语言,DI不能弄明白应该通过参数类型注入哪一个service
显式依赖:要通过$inject属性指定service名称, 它是一个包含需要注入的service名称的字符串数组,工厂方法中的参数顺序,与service 在数组中的顺序一致。
隐式依赖:则允许通过参数名称决定依赖,$scope
例子:
index.html
<div ng-app="myApp">
<div ng-controller="firstController">
</div>
<div ng-controller="secondController">
</div>
<div ng-controller="otherController">
</div>
</div>
<script type="text/javascript" src="../../vendor/angular/angularjs.js"></script>
<script type="text/javascript" src="app/index.js"></script>
var myApp = angular.module('myApp', [], ['$filterProvider', '$provide', '$controllerProvider', function (a, b, c) {
console.log(a, b, c);
}])
.
factory('CustomService', ['$window', function (a) {
console.log(a);
}])
// 隐示的依赖注入
.controller('firstController', function ($scope, CustomService) {
console.log(CustomService);
})
// 显示的依赖注入
.controller('secondController', ['$scope', '$filter', function (a, b) {
console.log(b('json')([1, 2, 3, 4, 5]));
}]);
function otherController(a) {
console.log(a);
}
otherController.$inject = ['$scope'];
Last updated
Was this helpful?