如何检查是否有angularjs控制器已经被定义 [英] How to check if an angularjs controller has been defined

查看:306
本文介绍了如何检查是否有angularjs控制器已经被定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样定义的应用程序:

I've got an app defined this way:

angular.module("myApp", [...])
  .config(function ($stateProvider, $controllerProvider) {
    if (isControllerDefined(controllerName)) {
      do_stuff();
    }
  })

该控制器的定义是这样的:

The controllers are defined this way:

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?

推荐答案

这可以检查是否控制器存在服务的一个例子。请注意,它看起来对全局函数以及在 $控制器控制器人员。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆