2012-09-22 42 views
11

在angularjs中,給定一個模塊,如何檢查給定模塊是否存在指令/控制器。如何使用Angularjs檢查模塊中是否存在指令或控制器

我有一個模塊,我想知道是否一些特定的指令已被加載。以下是一些示例代碼:

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 
} 

我已經以某種方式實現了這一點。如果缺省情況下可用,請尋找更好的方法。

這可能嗎? 如果是這樣,你是如何做到這一點的?

+0

您想在模塊的配置階段找出那些控制器/指令嗎?或者在應用程序被引導(run())階段執行後)? –

+0

任何會爲我做。無論如何,在我執行檢查之前,應用程序將使用angular.bootstrap(el,[myModule]) ritcoder

回答

9

使用此代碼來檢查服務是否存在。

$injector.has('myServiceName')

要檢查指令存在,你必須在指令名後添加Directive後綴:

$injector.has('myDirectiveNameDirective')

-3

通過編寫一個被調用來加載控制器和東西的包裝函數來解決這個問題,並且在這種情況下我可以知道每個指令何時加載。

+11

引導。您是否可以分享此代碼? – CMCDragonkai

3

我發現了一些工作代碼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/

2
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 
    } 
相關問題