dhuyvetter
dhuyvetter

Reputation: 594

How to read an Angular expression in plain old JavaScript

The Angular app I am working on has to read the Google Analytics ID from Angular to pass it to ga('create', 'UA-XXXXX-Y') in standard JavaScript on my index.html

<!-- Google Analytics: change UA-XXXXX-X to be your site's ID -->
<script>
   !function(A,n,g,u,l,a,r){A.GoogleAnalyticsObject=l,A[l]=A[l]||function(){
   (A[l].q=A[l].q||[]).push(arguments)},A[l].l=+new Date,a=n.createElement(g),
   r=n.getElementsByTagName(g)[0],a.src=u,r.parentNode.insertBefore(a,r)
   }(window,document,'script','//www.google-analytics.com/analytics.js','ga');

   ga('create', $rootScope.googleAnalytics );
   // ga('send', 'pageview');
</script>

The app will serve more then one website and so the Google Analytics code will be change according to the website being served.

The code ga('create', $rootScope.googleAnalytics ); isn't working, throwing an Uncaught ReferenceError: $rootScope is not defined.

The Google Analytics ID is also in a cookie, so I could read it from the cookie in my JavaScript, but isn't there an easier way to do this?

UPDATE: I've gone the route of not putting the GA id in the $rootScope but only in a cookie and calling ga('create', gaFromCookie) in the controller after the cookie is set and not on index.html.

Upvotes: 1

Views: 126

Answers (1)

scniro
scniro

Reputation: 16989

The error you are receiving is because this script is running before your angular app is bootstrapped - so we have no idea what a $rootScope is at this point. You could instead call ga() after your app is initialized, or depending on whenever you define $rootScope.googleAnalytics. Observe the following example, where we call a "plain old" function in our module run phase. This would likely be a good place to then call ga(). Observe the following example...

function init(value) {
    ga('create', value);
}

angular.module('app', []).run(function($rootScope) {

    $rootScope.googleAnalytics = 'something'
    init($rootScope.googleAnalytics);
});

JSFiddle Link - simple demo

Upvotes: 1

Related Questions