3

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?

1 Answer 1

3

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

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

3 Comments

It should be the same also for constant, right? EDIT: tried in the plunker, it is.
Yes, you can also use constant. I just don't like to call a constant something that actually changes :)
Agreed, I was curious to verify if constant was truly a constant. Seems like it's not.

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.