3

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 Answers 2

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

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

3 Comments

Thank you... it was so easy!
@PankajParkar could you take a look at my question? For some reason I cannot attach a value to my ng-model when I check a box I get the following error - TypeError: Cannot assign to read only property 'entityChecked'. Here is my question if you have the time - stackoverflow.com/questions/35276014/…
Will look at it..once i will have machine.
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

1 Comment

I marked as a correct answer the first one, thanks for your time.

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.