Search code examples
javascriptangularjsionic-frameworkmixpanel

Ionic Run Function on Every State Change


I am integrating Mixpanel Analytics into my app and I want to track every state change and be able to submit some additional parameters. It would be best if there was a single location to do this rather than adding the tracking code to every controller.

I want to run something similar to this:

mixpanel.track("Page Change", {"state":$state.current.name})

on every state change. What is the best way to do this?


Solution

  • The best way to do this is probably an ui-router thing, not an ionic thing:

    angular.module('myApp')
      .run(function () {
        $rootScope.$on('$stateChangeStart', function () {
          // do thing
        })
      })
    

    Put it in a run block that will run when your app instantiates. There is also a $stateChangeSuccess event.

    Edit: I said it was an angular thing, but it's a ui-router thing, but I think ionic uses ui-router by default.