Angular JS, be mindful of checkbox status when filtering

I am trying to create a checkbox list 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 checkbox status is not saved when I scroll through the search box. For example, when I check "Green", I type something else in the textbox and then delete that text, marked "Green" is no longer checked. How can I have "memory" in checkbox status?

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

+3


source to share


2 answers


I suggested that you add one more property to your array items

each item

, which will be available asitem.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>

      

Worker Plunkr

+3


source


attach ng-model="item.checked"

to a checkbox like:

<input type="checkbox" ng-model="item.checked" id="{{item.id}}" value="{{item.id}}">{{item.name}}

      



see this plunker

+1


source







All Articles