0

I need to inject an extra object to my controllers dynamically so I thought it'd be best to do it in the run function like so:

angular.module("app").run([
    "$rootScope", "$inject", "repository.user", function ($rootScope, userRepository) {
        $rootScope.$on("$routeChangeStart", function (event, next, current) {
            var controller = next.$$route.controller;
            userRepository.getSession(function(data) {
                // What do do now?
            });
        });
    }
]);

I'd like to inject that returned data into my controllers but I'm not sure how to do it?

CallumVass
  • 11,288
  • 26
  • 84
  • 154

2 Answers2

0

Take a look at the $routeProvider documentation, specifically the resolve configuration option for a route. Have you thought about using this to dynamically resolve your dependency?

resolve - {Object.=} - An optional map of dependencies which should be injected into the controller. If any of these dependencies are promises, the router will wait for them all to be resolved or one to be rejected before the controller is instantiated. If all the promises are resolved successfully, the values of the resolved promises are injected and $routeChangeSuccess event is fired. If any of the promises are rejected the $routeChangeError event is fired. The map object is:

  • key – {string}: a name of a dependency to be injected into the controller.

  • factory - {string|function}: If string then it is an alias for a service. Otherwise if function, then it is injected and the return value is treated as the dependency. If the result is a promise, it is resolved before its value is injected into the controller. Be aware that ngRoute.$routeParams will still refer to the previous route within these resolve functions. Use $route.current.params to access the new route parameters, instead.

Andrew Church
  • 1,391
  • 11
  • 13
  • Yes, I tried it via resolve but I can only inject Providers into a `config` and I cant then use $http from my provider, see: http://stackoverflow.com/questions/23657476/angular-using-http-in-a-provider/23658078 . So I thought I'd try it this way? – CallumVass May 14 '14 at 15:39
  • Take a look at this one: http://stackoverflow.com/questions/17497006/use-http-inside-custom-provider-in-app-config-angular-js - could you use that to configure your service? – Andrew Church May 14 '14 at 15:47
0

If I understand correctly, you are trying to collect user login state for every route change. Why not just save the data in $rootScope as something like $rootScope.currentUser = data.

This way you can access $rootScope.currentUser from any controller.