如何检查是否定义了 angularjs 控制器 [英] How to check if an angularjs controller has been defined
问题描述
我有一个这样定义的应用:
I've got an app defined this way:
angular.module("myApp", [...])
.config(function ($stateProvider, $controllerProvider) {
if (isControllerDefined(controllerName)) {
do_stuff();
}
})
控制器是这样定义的:
angular.module("myApp")
.controller("myController", function ($scope) { ... });
如果我有控制器的名称,我如何定义 isControllerDefined()
(在上面的配置中)来检查给定的控制器是否存在?我觉得我应该能够做这样的事情之一:
How can I define isControllerDefined()
(in the config above) to check whether a given controller exists if I have the name of the controller? I feel like I should be able to do something like one of these:
var ctrl = angular.module("myApp").getController("myController");
var ctrl = $controllerProvider.get("myController");
或类似的东西......但我找不到任何功能.有帮助吗?
or something like that... but I can't find any functionality for this. Help?
推荐答案
一个可以检查控制器是否存在的服务示例.请注意,它会在 $controller
全局函数以及控制器> 提供商.
An example of a service that can check if a controller exists. Note that it looks for a global function with specified name as well as a controller in the $controller
provider.
angular.service('ControllerChecker', ['$controller', function($controller) {
return {
exists: function(controllerName) {
if(typeof window[controllerName] == 'function') {
return true;
}
try {
$controller(controllerName);
return true;
} catch (error) {
return !(error instanceof TypeError);
}
}
};
}]);
有关用法,请参阅小提琴.
这篇关于如何检查是否定义了 angularjs 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!