AngularJS mantain state when changing views? - angularjs

Is there a way to maintain $scope when changing views and coming back?
When i load a certain view there is some heavy loading (loading data), but if i switch views and comeback to this one al the data is reloading again. Is there a way to prevent this?
I am not looking to share data between views, I just wish to have the old state when I return to the same view.

There's a few ways to handle this.
$rootScope
You might be able to store the values in the $rootScope, I don't believe it changes when you use the internal routing module, but I would not recommend this.
Services (My Immediate recommendation)
You can use a static service, where the data can be stored, either constantly, or while changing route. Then you can load the data into the $scope again.
Caching
AngularJS has an inbuilt cache, you can use. This is great if you only need to store some of it, or for a smaller amount of time. Read the documentation for the CacheFactory here.
WebSQL or localstorage
For large amounts of data, you want to store between sessions, you can use the WebSQL database in most browsers, or store it as text in the localStorage in the browser.

Related

What is the best way to store static data from API with AngularJs?

I wonder what is the best practice for storing lists from different API's and display them without the need to make redundant API requests.
Suppose user logged in - i want to store all the pages static lists for dropdown menus in a way that they will be available to all the controllers - by doing the API requests once.
The options that i came across are the following:
creating a factory and store the data in $rootScope.
Use sessionStorage.
What is the best way?
Consider storing data in rootscope a very bad practice.
I'd suggest using this package
https://github.com/jmdobry/angular-cache
You have nicely explained inside documentation why would you use this package instead of angulars built in $cacheFactory service.

AngularJS need to store userdata , should be available to entire application

I need to store userdata, should be available to entire application, should be accessible to required controllers, after searching I found a few options to store.
using a service to controllers
$sessionStorage
$localStorage
of all the above could u please tell me which is the best practice? Or is there any other solution other than the above 3.
Using a simple google search might have told you a lot about the best thing? there is no single best thing it's all depends upon your use case.
Services are the best way to interchange data between controllers.
if you don't want to persist the data(if data don't want to be there if the page is reloaded) you can use a service, If you want to persist the data you can use localstorage.

Angular app lifetime in a browser

I tried to google the following question, but nothing came up (which is super weird I need to).
What is an Agular app lifetime in a browser?
Or to rephrase when a user opens an Angular website, the app instances in the browser and stays live until the user leaves the website or closes the browser or?
On the separate note is it better to use a service for holding global variables (e.g. logged user name) or $rootScope?
Thanks!
What is an Agular app lifetime in a browser?
The angular app persists while that particular tab/site is open. If you navigate away from it and then back to it, for all intents and purposes, that's a fresh instance of the application. You could mimic a persistent session but that would entail a custom implementation on your part.
Here is a post on preserving data on a refresh of the application that you might be interested in - AngualrJS: sustaining data on html refresh
On the separate note is it better to use a service for holding global variables (e.g. logged user name) or $rootScope?
This is well documented and you can find myriad sources both here on SO as well as the internet, but it's better to use an angular service to share data among various controllers. It's not recommended that you pollute the $rootScope if you can avoid it.
Here is the same question asked on SO with solutions:
angular set a variable accessible to any scope
How to use variables from a controller in another controller in AngularJS
If you use angular's routing or another way to load views that doesn't reload a page, then an angular application will stay active until you leave the page (closing or refreshing).
Every time you load a page through angular its controller's data is in its initial state so any modification to a controller's data will get lost when you change page (unless you persist it somewhere, that is)
Regarding your second question, the best way should be to get a user's data after every page change (to check if the user is still logged in. Saving a user's data client side without checking if it's still valid might be a security issue). But in any case, a service is a better way to store data than using rootScope

ANGULARJS How to keep controllers tidy when managing view logic?

After reading these articles I've been trying to decouple my app:
http://toddmotto.com/opinionated-angular-js-styleguide-for-teams/
http://toddmotto.com/rethinking-angular-js-controllers/
One of the insight of the articles is this one:
Controller drives Model changes, and View changes. Keyword; drives,
not creates/persists, it triggers them!
I've found easy to manage persistent data in my services but I still need to create data in the controllers to handle view state changes or transforming data from the services.
Is there a pattern to avoid creating ANY data in the controller while being able to manage the view?

The best way to pre-populate remote data in AngularJS app

In my AngularJS app, I need to retrieve multiple collections of static data from remote REST endpoints. Those data collections will be used throughout the entire application life cycle as static lookup lists. I would like for all those lists to be populated upon the initial application startup, and to be retained and made available to multiple controllers. I would prefer not to load any additional data dynamically, as one of the assumptions for this particular app, is that, once loaded, any further network connections may not be available for a while.
It is OK to take an initial hit, as the users will be preoccupied by reading a static content of the first page anyway.
I was thinking of making this mass loading a part of the initial application run block, and stick all this static data into various collections attached to the $rootScope (which would make that available everywhere else)
What is the best way to handle this requirement?
Interestingly enough, I just wrote a blog post about extending the script directive to handle this very scenario.
The concept is simple. You embed JSON data in your page when it loads from the server like so:
<script type="text/context-info">
{
"name":"foo-view",
"id":34,
"tags":[
"angular",
"javascript",
"directives"
]
}
</script>
Then you extend the script directive so it parses the data out for you and makes it available to other parts of your application via a service.
if(attr.type === 'text/context-info'){
var contextInfo = JSON.parse(element[0].text);
//Custom service that can be injected into
// the decorator
contextInfoService.addContextInfo(contextInfo);
}
You can see a live demo of it here: http://embed.plnkr.co/mSFgaO/preview
The way I approach this is to use a service (or a collection of services I nest), and set caching to true in the $http get functions. This way the service can be passed into any controller you desire, having cached results available to you without the need for additional http requests.
I can try to put this into an example if this is unclear to you, let me know.
edit: you can either wait for the first call to this service to do this caching, or do this on app load, either way is possible.

Resources