Angular $injector——为Angular提供的未知提供商's $timeout
Angular $injector - Unknown Provider for Angular's $timeout
我试图在一个应该在我的应用程序中的几个控制器中调用的方法中注入angular的$timeout
服务。然而,我总是得到错误:
错误:[$injector:unpr]未知提供商:$timeoutProvider <->$timeout
当然$timeout
必须是已知的,因为它是一个angular服务,所以我不明白为什么会发生这个错误。
这是我的代码:
HTML:
<div ng-app="app" ng-controller="sampleController">
<button ng-click="doit()">Do It!</button>
</div>
JAVASCRIPT:
var app = angular.module('app', []);
app.controller('sampleController', ['$scope', function($scope) {
var _this = this;
$scope.doit = function() {
var $injector = angular.injector();
var $timeout = $injector.get('$timeout', _this);
$timeout(function () { alert('ok'); });
};
}]);
下面是演示这个问题的示例:
https://jsfiddle.net/fvw8zss5/- 这不是一个关于这是否是一个坏做法的问题。这当然不好。这是一个关于为什么不工作的问题。 如果你知道如何使用JsFiddle, JsFiddle将工作。
angular.injector()只能在每个应用中使用一次,而不能在每个模块中使用。你应该通过DI使用$injector来获得实例化的注入器。话虽如此,将ng模块添加到列表中可以通过创建一个新的注入器来"解决"这个问题(不推荐)
我想我明白你的意思了,你想要一个函数对所有25个控制器可用,而不必为所有25个控制器做依赖注入,你不想做一个服务,因为你必须把这个服务注入到所有25个控制器。
老实说,如果你想让这个函数在25个控制器上可用,你将不得不在所有25个控制器上做一个DI,无论是$timeout, service还是$rootScope方法
假设这25个控制器都没有父控制器,下面是$rootScope版本:
angular.module('fooApp').run(['$rootScope', '$timeout', function($rootScope, $timeout) {
$rootScope.doit = function() {
//Insert function here with $timeout
};
}]);
你必须在所有的控制器中注入$rootScope来运行这个函数。
我认为你最好的选择是使用一个服务,或者至少下次设置你的应用程序,这样你就有了一个父控制器。为什么不直接把它注入到你的控制器声明中呢
app.controller('sampleController', ['$scope','$timeout', function($scope,$timeout)
为什么不使用指令而不是在每个控制器中重复工作?
<div ng-app="app" ng-controller="sampleController">
<button do-it>Do It!</button>
</div>
脚本端:
app.directive('doIt', function ($timeout) {
return {
restrict: 'A',
link: function ($scope, $element, $attr) {
$element.on('click', function () {
$timeout(function () { alert('ok'); });
});
}
};
});
相关文章:
- Angular JS IE9 Hashbang url rewriting
- 如何在Angular中用$timeout包装承诺链
- 在 Karma/Jasmine 单元测试中注入 Angular $timeout服务的真实实现
- 为什么 Angular 摘要循环在 UI 事件、$timeout和$http上有所不同
- 刷新后的angular$timeout
- angular$timeout在3秒后重定向
- 如何使用$resource在angular js中使用$timeout
- $timeout保证在angular js中实现缓存服务
- 使用$timeout强制Angular中的摘要
- 自定义表单验证器在Angular 1.3中失败,返回$timeout和$setValidity
- Angular $injector——为Angular提供的未知提供商's $timeout
- 在angular js中使用$timeout来重复rest调用
- Angular:如何访问$timeout callback之外的参数
- Angular timeout
- Angular, Jasmine——监视在$interval/$timeout服务中执行的函数
- Angular Js回调函数$timeout
- 如何使用$timeout在Angular中执行一系列事件
- Chaining angular $timeout
- Angular $http config timeout
- set Timeout中的Angular变量没有刷新