javascript 如何使用 Angularjs 检查模块中的指令或控制器是否可用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12544125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:28:39  来源:igfitidea点击:

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

javascriptangularjs

提问by ritcoder

In angularjs, given a module, how do you check if a directive/controller exists given a module.

在 angularjs 中,给定一个模块,如何检查给定模块的指令/控制器是否存在。

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?

这可能吗?如果是这样,你怎么做?

回答by Pian0_M4n

Use this code to check if a service exists.

使用此代码检查服务是否存在。

$injector.has('myServiceName')

$injector.has('myServiceName')

To check if a directive exists, you must add a Directivesuffix after the directive name:

要检查指令是否存在,您必须Directive在指令名称后添加后缀:

$injector.has('myDirectiveNameDirective')

$injector.has('myDirectiveNameDirective')

回答by jlewkovich

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/

JSFiddle:http: //jsfiddle.net/fracz/HB7LU/6780/

回答by sgarbesi

    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
    }

回答by ritcoder

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.

通过编写一个包装函数来解决这个问题,该函数被调用来加载控制器和东西,这样我就可以知道每个指令何时加载。