0

i have a problem with global variables in Angular.js framework, there are controllers handling array of objects in my application. So i need to update this variable in all controllers when i make 'GET' request to the server for a new data.

I tried do it with services, but the array changes only in controller which initiates get request.

How i can do this?

2
  • where is the code you have problems with? Commented Nov 14, 2014 at 7:39
  • update it with $rootScope then changes will be reflected every where. Commented Nov 14, 2014 at 8:01

2 Answers 2

1

So do you want to know how to share global variables across contollers?

That you can do with the $rootScope:

https://docs.angularjs.org/api/ng/service/$rootScope

So you just work with $rootScope.yourArrayOfObjs = ....

Also have a look at what the different scopes are in ng

https://docs.angularjs.org/guide/scope


UPDATE: You can of course also do this with a service but not if the sole purpose of the service is to provide the global variables. See angular FAQ last question:

https://docs.angularjs.org/misc/faq

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

1 Comment

Thanks for the update with the link to the FAQs. I was surprised by the last sentence because I thought all scopes (also isolate scopes) would inherit from $rootScope, which would make them a bad place to store such data. However, I found out that this is not the case. Anyway, unless the data is used nearly everywhere in the app, I'd rather wrap it in a service and inject it where appropriate.
0

This is a common issue, and you need to store your data in (rather than as) an object in your factory, like:

app.factory('Factory', function() {
    var Factory;
    Factory.data = {}
    Factory.data.sharedAccrossControllers = [1,2,3];
    return Factory;
});

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.