Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS, remember checkbox status when filtering

I'm trying to create a list with checkboxes with a search box.

HTML

  <div ng-controller="MainCtrl">
    <input type="text" placeholder="Search" ng-model="query">
    <div ng-repeat="item in items | filter:query">
      <input type="checkbox" id="{{item.id}}" value="{{item.id}}">{{item.name}}
    </div>
  </div>

JS

myApp.controller('MainCtrl', function ($scope) {
  $scope.items = [
    {
      "id": 1,
      "name": "Green",
    },
    {
      "id": 2,
      "name": "Yellow",
    },
    {
      "id": 3,
      "name": "Blue",
    },
    {
      "id": 4,
      "name": "Red",
    }
  ];
});

The problem is that the checkboxes status are not saved when I'm searching through the search box. For example, when I check "Green", I type on text box something else, then remove this text, the checked "Green" is not checked anymore. How can I have "memory" on checkboxes status?

Here is a link to plunker: http://plnkr.co/edit/KHq3AA4guGKA4AqxQrF8

like image 420
MatthewK Avatar asked Aug 29 '26 09:08

MatthewK


1 Answers

I'd suggested you to add one more property in your items array each item, that would be accessible as item.checked

Markup

  <div ng-controller="MainCtrl">
    <input type="text" placeholder="Search" ng-model="query">
    <div ng-repeat="item in items | filter:query">
      <input type="checkbox" ng-model="item.checked">{{item.name}}
    </div>
  </div>

Working Plunkr

like image 185
Pankaj Parkar Avatar answered Sep 04 '26 00:09

Pankaj Parkar