Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS change injected global variable value

I have a constant app.constant('DOCUMENT_ID', window.documentId || 1); which I inject into services, controllers and directives.

I want to change DOCUMENT_ID to be a global variable, so that if I change DOCUMENT_ID's value in controller, I want to get the changed value in all services and controllers in which DOCUMENT_ID was injected.

How can I use a global variable in this way?

like image 781
Algirdas Avatar asked Sep 22 '26 02:09

Algirdas


1 Answers

You don't need global variable here (plus it's a bad practice). Just make use of the fact that objects are passed by references. For example you could use a service defined like this:

app.value('DOCUMENT', {
    ID: window.documentId || 1
});

Now, whenever you change DOCUMENT.ID anywhere, every part of the application will have updated version of ID. Just read it like object property.

Demo: http://plnkr.co/edit/Oay8IaLRnuCN2xkSuM69?p=preview

like image 96
dfsq Avatar answered Sep 24 '26 14:09

dfsq



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!