How to inject $location into a click event handler defined in a config function

531 views Asked by At

I am amending some code that is a plugin to an AngularJS analytics framework. In the plugin, I would like access to the $locationobject within what is essentially a $routeChangeSuccess handler. The event handler is defined in a config function, but when the code actually executes, my understanding is that $location should be available.

The following doesn't work:

angular.module('myModule', ['angulartics'])
.config(['$analyticsProvider','$injector', function ($analyticsProvider, $injector) {
  $analyticsProvider.registerPageTrack(function (path) {
    // The following runs on $routeChangeSuccess
    $injector.invoke(['$location',function($location) {
      try {
          analytics.page({
            path: path,
            url: $location.absUrl()
          });
      } catch (e) {
          if (!(e instanceof ReferenceError)) {
              throw e;
          }
      }
    }]);
  });

  $analyticsProvider.registerEventTrack(function (action, properties) {
    try {
      analytics.track(action, properties);
    } catch (e) {
        if (!(e instanceof ReferenceError)) {
            throw e;
        }
    }
  });
}]);
})(angular);

In this case, the $injector cannot find the $location service. In digging a little further, I found out that is because the injector I have is actually the provider injector (because that is what is given to me by the config function) and not the instance injector (which has $location).

Is there any way for me to get the instance injector, rather than the provider injector? I am pretty sure that the instance injector is fully available when the code actually runs. If I'm wrong on that, then I'd like to know too! Thanks!

0

There are 0 answers