Angular JS, remember checkbox status when filtering

时间:2015-05-04 19:26:29

标签: angularjs checkbox ng-repeat angularjs-filter

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

2 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:1)

attach ng-model="item.checked" to checkbox like:

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

see this plunker