Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 445
Sir Robert Avatar asked Nov 01 '13 20:11

Sir Robert


People also ask

What are the controllers in AngularJS?

AngularJS Controllers AngularJS applications are controlled by controllers. The ng-controller directive defines the application controller. A controller is a JavaScript Object, created by a standard JavaScript object constructor.

Which is the valid statement of controller in AngularJS?

ng-controller directive tells AngularJS what controller to use with this view. AngularJS application mainly relies on controllers to control the flow of data in the application.

Which is the correct syntax of creating AngularJS controller?

13) Which of the following syntax is used to create a module in AngularJS? Answer: C is the correct option. To create a module in AngularJS, we use angular. module("app", []); syntax.

What is $$ in AngularJS?

The $ in AngularJs is a built-in object.It contains application data and methods.


Video Answer


3 Answers

There is currently no easy way of fetching a list of controllers. That is hidden for internal use only. You would have to go to the source code and add a public method that return the internal controllers variable (in $ControllerProvider function) https://github.com/angular/angular.js/blob/master/src/ng/controller.js#L16

this.getControllers = function() {
    return controllers;
    // This will return an object of all the currently defined controllers
  };

Then you can just do

app.config(function($controllerProvider) {
    var myCtrl = $controllerProvider.getControllers()['myController'];
});
like image 176
trekforever Avatar answered Oct 12 '22 03:10

trekforever


I came across this exact same issue the other day. I had a few issues with the currently accepted answer, namely because one of my controllers was performing an initialization call out to the server upon instantiation to populate some data (i.e):

function ExampleController($scope, ExampleService) {
    ExampleService.getData().then(function(data) {
        $scope.foo = data.foo;
        $scope.bar = data.bar
    });
}

As it stands, the currently accepted answer will actually instantiate the controller, before discarding it. This lead to multiple API calls being made on each request (one to verify that the controller exists, one to actually use the controller).

I had a bit of a dig around in the $controller source code and found that there's an undocumented parameter you can pass in called later which will delay instantiation. It will, however, still run all of the checks to ensure that the controller exists, which is perfect!

angular.factory("util", [ "$controller", function($controller) {
    return {
        controllerExists: function(name) {
            try {
                // inject '$scope' as a dummy local variable
                // and flag the $controller with 'later' to delay instantiation
                $controller(name, { "$scope": {} }, true);
                return true;
            }
            catch(ex) {
                return false;
            }
        }
    };
}]);

UPDATE: Probably a lot easier as a decorator:

angular.config(['$provide', function($provide) {
    $provide.delegate('$controller', [ '$delegate', function($delegate) {
        $delegate.exists = function(controllerName) {
            try {
                // inject '$scope' as a dummy local variable
                // and flag the $controller with 'later' to delay instantiation
                $delegate(controllerName, { '$scope': {} }, true);
                return true;
            }
            catch(ex) {
                return false;
            }
        };

        return $delegate;
    }]);
}]);

Then you can simply inject $controller and call exists(...)

function($controller) {
    console.log($controller.exists('TestController') ? 'Exists' : 'Does not exist');
}
like image 35
Jason Larke Avatar answered Oct 12 '22 03:10

Jason Larke


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.

like image 9
fracz Avatar answered Oct 12 '22 03:10

fracz