AngularJs – Saving global variable into localStorageService

Hey,

I have interesting task with AngularJs (Just trying learn AngularJs and expand my knowledge here). Let me explain what I want to achieve. For example we have app for finding accommodation(s). One list represents flats another houses. As end user we want have a possibility mark them as favorites to have checklist where we can go later and find what we interested in.  So in general we have two (or more) lists and possibility check them and have on summary list with our favorites.

In such case usually we think about session, some static data. In .Net world we share singleton instance through the application pool. Cache, session it’s what we think about independently of implementation : memory, file, database…

In AngularJs basically we have two options :

use a $rootScope http://docs.angularjs.org/api/ng.$rootScope
use a service http://docs.angularjs.org/guide/services

Services are singletons that you can inject to any controller and expose their values in a controller’s scope. Yeah, the first thought I came with…… Services, being singletons are still ‘global’ but you’ve got far better control over where those are used and exposed. In the mean time $rootScope is a parent of all scopes so values exposed there will be visible in all templates and controllers.

Let’s say I have bigger dreams. I want to have persistent data, which means when you close your browser and will come back later you have this favorites listed down upfront. Not a big deal using cookies right ? I found that there is a solution for angular which deals with local browser storage called : “angular-local-storage”. Installation is very simple by typing command below :

bower install angular-local-storage

Ok, welcome on board local storage. Need to mention that we have cookies support as a fallback. Yeah, it’s even better than deal with cookies directly.

Let’s go back to the requirements I came from :

somehow by pressing favorite button I want to add item in the list (global variable) and without writing any single line of code, sync that data immediately with local storage.

local storage itself has function called binding : localStorageService.bind(scope, key, def);

// Example
$scope.list= {'Id':'1', 'Type':'Flat', 'Name': 'Flat Name 1'};

// Bind to local storage service
localStorageService.bind($scope, 'favorites', list);

// get bound data:
console.log(localStorageService.get('favorites'));

From example above you can see how we have bound local controller variable to the local storage.

It’s time create simple service and bind variable there :

'use strict'; /** * @ngdoc service * @name kartaEziukasPasakeOpApp.fsUtils * @description * # fsUtils * Service in the kartaEziukasPasakeOpApp. */ angular.module('kartaEziukasPasakeOpApp') .factory('fsUtils', function fsUtils(fsApi, localStorageService, $rootScope) { var fsUtils = {

favorites : localStorageService.get('favorites') || [], addFavorite: function (item) { fsUtils.favorites.push(item);

}}; localStorageService.bind($rootScope, 'favorites', sUtils.favorites);

return fsUtils;

});

and controller as well :

'use strict'; angular.module('kartaEziukasPasakeOpApp') .controller('AccomodationsCtrl', function ($scope, fsApi, fsUtils) { var collectionName = 'Accomodations'; // call to API and get data fsApi.get(collectionName).then(function (data) { $scope.list = data; });       // occurs when fave has been checked       $scope.addFavorite = function (viewName, item, allowMultiple) { fsUtils.addFavorite(item);

}; });

I’m not deep dive into full implementation here, but from now you are able work with global variable called – favorites. When you add item into list you can be sure that data will be persisted to local storage of the browser or to cookie as a fallback.

What’s next. In my opinion use case which I covered is to simple. Later on I will try do more sophisticated things like :

  1. load list from database and apply changes from local storage
  2. split favorites into several lists or have one list with types like : accommodations, flights, boats…
  3. When you are logged in then play with database or web service directly, otherwise play with handy local storage. On registration or login part persist data to database or web service
  4. Play more in smart way – create events (emit, boradcasting) and handlers (controller initialization)

I hope I will have time to share this information later, so stay tuned 😉

Posted in Development

Leave a comment