VISHAL DAGA
VISHAL DAGA

Reputation: 4289

Angular - Injecting locationProvider inside app constant

I wish to inject location provider in the module constant, which is not possible

app.constant('foo', {
    hostName: <<$location.$$root>> //which is not possible.
}

so, I tried this:

app.provider('foo', ['$locationProvider', function($locationProvider) {
    this.data = {
        hostName: $locationProvider.$$root + ":1337"
    };
    this.$get = function() {
        return this.data;
    };
}]);

But again this didn't work, as $locationProvider.$$root is undefined.

Any solution/s ?

Upvotes: 0

Views: 344

Answers (1)

tmarwen
tmarwen

Reputation: 16354

Module constants in AngularJS are meant to register a value / object that can be accessed by a Provider, so basically you cannot go the other way, by trying to use Provider services within your Constant declaration.

A hack for such a situation would be to extract manually the value that you want pulled of, i.e. the root page location, from the window.location JavaScript object:

app.constant('foo', {
    hostName: window.location.protocol + window.location.host // .host gives you the page hostname appended with the port used to render the page
}

Just remember that plain JavaScript objects provided by most web browsers are still out there when AngularJS cannot do the job.

Upvotes: 2

Related Questions