本文介绍了AngularJS 动态注入作用域或控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以在运行期间注入作用域或控制器?或任何其他建议将服务动态注入控制器?
Is it possible to inject scope or controller during running ?or any other advice to dynamically inject services into controller ?
Application.controller('IndexController', function($scope){
// some actions
if(someconditions) {
$scope.$inject = [someServiceName];
// and here i want to use service methods
}
});
提前致谢
推荐答案
可以使用 $injector.能够通过控制器参数注入服务只是 Angular 提供的一种便利.在幕后,Angular 使用 $injector 来检索对象实例.但是我们也可以自己使用 $injector.
A service can be dynamically injected (by name) into a controller using the $injector. Being able to inject services via controller arguments is just a convenience that Angular provides. Under the hood, the $injector is used by Angular to retrieve object instances. But we can use the $injector ourselves also.
function MyCtrl($scope, $injector) {
$scope.doSomething = function(someService) {
var service = $injector.get(someService) // someService contains the name of a service
service.value += 10
}
小提琴.
这篇关于AngularJS 动态注入作用域或控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!