Search code examples
angularjsconfigcontrollers

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

The controllers are defined this way:

angular.module("myApp")
  .controller("myController", function ($scope) { ... });

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?


Solution

  • 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.