In angularjs, given a module, how do you check if a directive/controller exists given a module.
I have a module and I want to know if some particular directives have been loaded. Below is some sample code:
var module = angular.module('myModule');
//check if controller exists
if (module.hasController('my.first.controller')){
//do something
}
if (module.hasDirective('my.first.directive')){
//do something
}
I have implemented this in a way. Looking for a better way of doing it if it is available by default.
Is this possible? If so, how do you do this?
The ng-app directive defines the root element of an AngularJS application and starts an AngularJS Application. The ng-app directive will auto-bootstrap (automatically initialize) the application when a web page is loaded. It is also used to load various AngularJS modules in AngularJS Application.
AngularJS ng-controller Directive The ng-controller directive adds a controller to your application. In the controller you can write code, and make functions and variables, which will be parts of an object, available inside the current HTML element. In AngularJS this object is called a scope.
A controller is usually used to contain and maintain the logic for your view, which gets bound to your view via $scope. A directive is something that you might use repeatedly and is called in your view directly through the directive name which you can pass in as an attribute.
You just create a myVar variable in your controller and pass it to the directive using my-var attribute. Since you are using two way binding, any changes made to myVar by the directive are available in your controller.
Use this code to check if a service exists.
$injector.has('myServiceName')
To check if a directive exists, you must add a Directive
suffix after the directive name:
$injector.has('myDirectiveNameDirective')
I found some working code here
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);
}
}
};
}]);
JSFiddle: http://jsfiddle.net/fracz/HB7LU/6780/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With