Angular,动态获取应用或模块名

Angular, get app or module name dynamically

本文关键字:模块 应用 获取 动态 Angular      更新时间:2023-09-26

我们在Angular中开发了一个SPA,我想在路由器发生变化时触发我的分析代码,所以我希望能够获得应用名或模块名。下面是我试图使用的代码,但我得到错误为"ReferenceError: testApp未定义(…)"。

function getAllElementsWithAttribute(attribute)
 {
   var matchingElements = [];
   var allElements = document.getElementsByTagName('*');
   for (var i = 0, n = allElements.length; i < n; i++)
   {
     if (allElements[i].getAttribute(attribute) !== null)
     {
       // Element exists with attribute. Add to array.
       matchingElements.push(allElements[i].getAttribute(attribute));
      }
   }
  return matchingElements[0];
 }
if(window.angular != undefined || window.angular != null){
   console.log("Angular lOADED");
   //var modName = angular.modules[0];  
   var modName = getAllElementsWithAttribute("ng-app"); 
   try{
     var myMod = typeof(eval(modName));
     console.log(myMod);            
   }catch(e){
     console.log(e);
  }
  myMod.run(function($rootScope, $location) {
    console.log($routeScope)
    $rootScope.$on('$routeChangeSuccess', function () {     
     if(true){
        loadTag($location);
     }
   });
 });
  function loadTag(location){
    console.log(location);
    console.log("Tag Loaded");
  }
}

你可以在路由配置中这样定义"names":

.state('dummy', {
        url: '/dummy',
        templateUrl: 'app/dummy.html',
        controller: 'DummyController',
        MyModuleOrTag: 'dummyTAg'
      })

你可以得到这样:

$state.current.MyModuleOrTag

我想这样查找每个元素会更快