Suraz Khanal Suraz Khanal - 1 year ago 62
AngularJS Question

How to save rows of multiple buttons value to localstorage in angularjs and ionic

Here i have ng-repeat which populate number of rows with the value from controller.And each row contain three buttons labeled as excellent , good and bad.What i want to make is save one value to localstorage with cval and button value from three buttons at each row. And selecting one should keep activate the button.

<div class="element" ng-repeat="cval in userOrderedValues track by $index">
<div class="values">
<div class="btns">
<button class="button button-balanced" ng-model="selected" ng-click="saveStatus($index,cval,'good')" ng-class="{'active':val=='good' && current==$index}">excellent</button>
<button class="button button-amber" ng-model="selected" ng-click="saveStatus($index,cval,'ok')" ng-class="{'active':val=='ok' && current==$index}">good</button>
<button class="button button-assertive" ng-model="selected" ng-click="saveStatus($index,cval,'nw')" ng-class="{'active':val=='nw' && current==$index}">bad</button>

How i can save these values to localstorage? this is codepen i have made for this

Answer Source

Angular has a module $cookies that does just this. To use it you'll first need to add the script to pull in the module, then you'll need update your main module's dependencies to include $ngCookies and finally in your controller you can inject $cookies.

One approach is to maintain an object that contains any selections. You can use $cookies.put() and $cookies.get() to interact with simple values such as strings and numbers but since we'll be dealing with objects we'll want to use $cookies.putObject() and $cookies.getObject().

Here's a plunkr with a simple example of how that might look. I tried doing it in your codepen fiddle but apparently codepen clears the cookies when the code changes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download