How to check if an angularjs controller has been defined

后端 未结 5 1618
被撕碎了的回忆
被撕碎了的回忆 2021-01-17 20:35

I\'ve got an app defined this way:

angular.module(\"myApp\", [...])
  .config(function ($stateProvider, $controllerProvider) {
    if (isControllerDefined(co         


        
5条回答
  •  心在旅途
    2021-01-17 20:55

    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);
          }
        }
      };
    }]);
    

    See the fiddle for usage.

提交回复
热议问题