Question

I have been looking for a way to get services on initialization of my angular-js application, but could not find how to get it to work. In my case I want to get the $location service to observe the url.

Looking around, I found the services can be retrieved from the injector. To get the injector, I bootstrapped my application like this:

var angularApp = angular.module("MyApp", []);
var angularInjector = angular.injector(["MyApp", "ng"]);
angularApp.run(initializeAngularApp);

initializeAngularApp()
{
    var location = angularInjector.get("$location");
}

This throws an Error:

Unknown provider: $rootElementProvider <- $rootElement <- $location

My understanding is that initializeAngularApp() should get called once the injector is done initializing. But judging from the error I get, it would not be the case.

What is the best way to get the services from the injector when my application initializes?

Was it helpful?

Solution

I found my answer and I did not need to instantiate the injector myself to get the service.

Services are injectable in the run() function, so doing:

angularApp.run(intializeAngularApp);

with

initializeAngularApp($rootScope, $location)
{
    $rootScope.location = $location;
    $rootScope.$watch("location.url()", function () { alert("url changed"); });
}

works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top