dmonaldo dmonaldo - 2 months ago 12
Javascript Question

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?

Answer

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.

Comments