2016-09-06 4 views
1

SPA가 Angular로 개발되었으며 라우터 변경시 분석 코드가 실행되기 때문에 앱 이름이나 모듈 이름을 가져오고 싶습니다. 아래 코드를 사용하려고하지만 "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"); 
    } 
} 
+0

요구에 따라로드하려면 require.js를 사용할 수 있습니다. 모듈에 대한 특별한 문서를보세요. https://github.com/johnpapa/angular-styleguide/blob/master/a1/README.md –

답변

0
이 같은 경로 구성의 "이름"정의를 할 수

:

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

그리고 당신은 다음과 같이 얻을 수 있습니다 :

$state.current.MyModuleOrTag 

내가 될 것입니다 이런 식으로 생각 각 요소를 더 빨리 검색 할 수 있습니다.

+0

안녕하세요. Fabio 님, 응답 해 주셔서 감사합니다. 그러나 제 지식을 용서합니다. 저는 Angular , 많은 응용 프로그램이 있으며 얼마나 많은 페이지 또는 페이지가 있는지 알지 못합니다. 그래서 나는 모듈 pr app 이름을 가져야하고 routechangesuccess에서 내 태그를 발사 할 것이라고 페이지 이름과 baed를 얻을 수있는 방식으로 내 코드를 실행하려고합니다. 나는 이것이 명확 해지기를 희망합니다 ... –

+0

이것을 보았습니까? [retrieve-anglesjs-app-name] (http://stackoverflow.com/questions/17502055/retrieve-angularjs-app-name)에서 AngularJS는 [$ rootElement] (https : //docs.angularjs. org/api/ng/service/$ rootElement). 이 요소에서 앱 이름을 찾을 수 있지만 모듈에 대해서는 검색 할 수 없다고 생각합니다. –

+0

예, 라우터 변경시 코드를 동적으로 실행하고 싶습니다. 어떻게 구현합니까? –

관련 문제