How to check if a directive or controller is available in a module using Angularjs

后端 未结 4 1770
情话喂你
情话喂你 2021-02-19 09:17

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 bee

相关标签:
4条回答
  • 2021-02-19 09:47

    Solved the problem by writing a wrapper function that is called to load the controllers and stuff and at such I'm able to tell when each directive is loaded.

    0 讨论(0)
  • 2021-02-19 09:49

    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')

    0 讨论(0)
  • 2021-02-19 09:58

    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/

    0 讨论(0)
  • 2021-02-19 09:58
        var controllers = [];
    
        _.each(app._invokeQueue, function(value, index) {
            if (value[0] !== '$controllerProvider') {
                return;
            }
    
            controllers.push(value[2][0]);
        });
    
        if (controllers.indexOf('controller-i-want') === - 1) {
            // controller is undefined
        }
    
    0 讨论(0)
提交回复
热议问题