2

I would like access to an $injectable when I create a constant in my angular app.

Is something like this possible? How would the injectable get declared?

    myApp.constant('myConfig', {     //where does $location get put?
        'searchUri': $location.blah() + "/e/_search?pretty",
        'version': 0.2
    });
3
  • 3
    From the angular docs: "The config method accepts a function, which can be injected with "provider" and "constant" components as dependencies. Note that you cannot inject "service" or "value" components into configuration." (docs.angularjs.org/guide/di) So you could inject $locationProvider, but not $location itself. Depending on what you want to do, it may be better to use run to grab values from $location and store them in a factory/service. Commented Apr 1, 2016 at 19:26
  • 1
    What is your use case for injecting services in a config constant? Commented Apr 1, 2016 at 20:25
  • @georgeawg my use case is basically what is in my question. I want a constant for something depends on what server it comes from. Since this is always the same for the life of the app, I figured I could get away with making it a constant. Commented Apr 1, 2016 at 20:28

1 Answer 1

1

In a config block, use angular.injector to create a temporary injector to instantiate a $location service. Then use that to create the myConfig constant.

angular.module('myApp').config(function($provide) {
    function tempRootElementProvider ($provide) {
        $provide.value("$rootElement", angular.element(document));
    }
    var tempInjector = angular.injector(['ng', tempRootElementProvider]);
    var tempLocation = tempInjector.get('$location');

    $provide.constant('myConfig', {
        'searchUri': tempLocation.absUrl() + "e/_search?pretty",
        'version': 0.2
    });
})

The $location service also depends on $rootElement, so that needs to be added as a dependency in the temporary injector.

The DEMO on JSFiddle.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.