Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override / change AngularJS value of value provider

I want to override value-

angular.module("data", []).value('apiBase', '/api1/data')

at runtime, I tried to modify it with-

angular.module("data").value('apiBase', '/someotherapi/data')

in some service/controller, but it failed, it didn't override the value of apiBase.

I tried to inject apiBase in my controller and change it.

angular.module('data').controller(function(apiBase){apiBase = '/someotherapi/data'})

it failed.

Then I tried change the apiBase defination to an object like

angular.module("data", []).value('apiBase', {"api_base_url":"/api1/data"})

then modifying it in controller:

angular.module('data').controller(function(apiBase){apiBase.api_base_url = '/someotherapi/data'})

It works. so my question is: why angular.module('data').value('samekey', 'newvalue') cannot override the value? why cannot modify the value when it is just a string/number (primary type. the second try). In my opinion Value provider is singleton, it should change.

like image 230
user2279962 Avatar asked Nov 25 '14 09:11

user2279962


1 Answers

Please read the documentation on how the dependency injection works in AngularJS.

Basically, AngularJS application is created in two phases - configuration phase and run phase. All configuration code, like registering a .value() with the special $provide service, is done during configuration phase. Once that phase ends, no more configuration can be done and the run phase begins, where your main module is bootstrapped to the DOM, controllers and services are instantiated, etc. This allows the dependency injection to work in a sane, deterministic manner (requesting an injectable by its ID always returns the same thing for the same ID).

like image 170
hon2a Avatar answered Sep 18 '22 20:09

hon2a