1

We have an SPA developed in Angular and I want to fire my analytics code when the router changes, so I want to be able to get the app name or the module name. Below is the code I am trying to use but I am getting error as "ReferenceError: testApp is not defined(…)".

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");
  }
}
1

1 Answer 1

0

You can do the "names" definition on the route configuration like this:

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

And you can get like this:

$state.current.MyModuleOrTag

I think in this way will be faster what search of each element

Sign up to request clarification or add additional context in comments.

3 Comments

Hi Fabio, thanks for the response but forgive my knowledge, I am pretty new to Angular, and there are lot of applications and I am not aware how many pages or what pages are there. So I want to fire my code in such a way that it should get the module pr app name and on routechangesuccess I'll get the page name and baed on that I''ll fire my tags. I hope this clarifies...
Have you saw this? retrieve-angularjs-app-name, in AngularJS we have access to $rootElement. In this element you can find the app name, but about the module i don't think its possible to retreive
Yes, but I want to fire my code dynamically when the router changes, how do I achieve that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.