Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ngCordova Google analytics ($cordovaGoogleAnalytics)

I am trying to use the 'https://github.com/danwilson/google-analytics-plugin.git' plugin with ngCordova. I have added the plugin and added ngCordova as a dependency in my controller.

when I try to set:

$cordovaGoogleAnalytics.startTrackerWithId('UA-XXXXXXXX-X'); 

I get this error: 'TypeError: Cannot read property 'startTrackerWithId' of undefined'.

I have set my analytics up as a mobile app in the Google dashboard.

Can anybody help with this?

like image 417
mcneela86 Avatar asked Nov 13 '14 13:11

mcneela86


2 Answers

That happens because you are trying to use analytics plugin before it's initialized by cordova.

Just wrap the initialization recursevely with a setTimetout:

function _waitForAnalytics(){
    if(typeof analytics !== 'undefined'){
        $cordovaGoogleAnalytics.debugMode();
        $cordovaGoogleAnalytics.startTrackerWithId('UA-XXXXXXXX-X');
        $cordovaGoogleAnalytics.trackView('APP first screen');
    }
    else{
        setTimeout(function(){
            _waitForAnalytics();
        },250);
    }
};
_waitForAnalytics();
like image 100
Fabio Antunes Avatar answered Nov 14 '22 04:11

Fabio Antunes


I think that this is the best way of tracking with google analytics

$ionicPlatform.ready(function () {
  $rootScope.$on('$stateChangeSuccess', function () {
    if(typeof analytics !== undefined) {
      analytics.debugMode();
      analytics.startTrackerWithId("UA-xxxxxxxx-x");
      analytics.trackView($state.current.name);
    } else {
      console.log("Google Analytics Unavailable");
    }
  });
});

This will track on each state change on the application and will give you the state that user is on.

like image 45
Ylli Gashi Avatar answered Nov 14 '22 02:11

Ylli Gashi