0

I want to make "checkbox are persistent" with localStorage when I reload my view are not lost.

The values that I'm saving the checked in localStorage with the help of ngStorage.

This is my code and demo https://jsfiddle.net/alx_lopz/bhgmw7ey/

<div ng-app="myApp">
    <div ng-controller="favCtrl">

        <div ng-repeat="chip in colores" >
            <input type="checkbox" name="{{chip.codigo}}" id="{{chip.codigo}}" ng-model="chip.checked" ng-change="chipsColores()"  ng-click="$storage.a = fav">
            <label>{{chip.codigo}}</label>
        </div>

        <div ng-repeat="favorite in $storage.a">
            localStorage: {{favorite.codigo}}
        </div>

    </div>
</div>

my controller:

(function(){

    angular.module('myApp',['ngStorage'])

    .controller('favCtrl',[ '$scope', '$filter', '$localStorage', function ( $scope, $filter, $localStorage) {
        $scope.colores = [
            {'nombre':'blue', 'codigo':'1111'},
            {'nombre':'green', 'codigo':'2222'},
            {'nombre':'red', 'codigo':'3333'}

        ];

        $scope.chipsColores = function () {
            $scope.fav = $filter('filter')($scope.colores, {checked: true});
        }
        $scope.$storage =  $localStorage.$default({
        });


    }])
})();

Please I need your help in my demo! Thanks...

2 Answers 2

1

What you want to do is probably to just store the map of the checked values - i.e. control ids (color ids) to it's checked state. So the key is to just update the map on ng-click:

$storage.a[chip.codigo] = chip.checked

and then use ng-checked="$storage.a[chip.codigo]". Please remember that it is also important to initialise map object first:

$localStorage.$default({
  a: {}  
});

here is updated fiddle https://jsfiddle.net/ciekawy/az2ehwon/

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

2 Comments

Thanks for the explanation and demonstration. That's what I wanted, but I have a problem when I uncheck the checkbox value does not disappear from view. How can I do that?. Sorry, I'm Beginning javascript and angular
You mean the fact that after unchecking i.e. 111 there is localStorage: 1111: false at the bottom? actually this is how you should use this. If for this diagnostic view you want to skip unchecked items, then it's enough to add ng-if="value" along with ng-repeat.
0

You can just save the data like this:

$scope.$storage = $localStorage.$default({
    someKey1: value1,
    someKey2: value2
});

Then the $scope.$storage object will be created with the default value. And saved into localStorage if some valued changed. You just need to bind the $storage object in view with some elements.

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.