Dexter
Dexter

Reputation: 3

AngularJS checkboxes dont remain checked if they are filtered away then returned

I have a list with checkboxes that can be filtered using a textbox as a search field

<input type="search" id="valSearch" value="" placeholder="Please type name..." class="search-input" ng-model="query">  
<ul class="list">
    <li class="list__item list__item--tappable" ng-repeat="name in classList | filter:query">  
         <label class="checkbox checkbox--list-item">  
             <input type="checkbox" class="chkProperty" value="{{id.childName}}">  
                {{id.childName}}  
        </label>  
     </li>  
</ul>  

The problem I am having is if a checkbox is selected and then a search is made, once the search field is cleared and the entire list is shown, the checkboxes that were selected do not remain checked when they return if they were hidden during the search. I've tried using jquery to check the boxes when they return as follows

$('#valSearch').on('keypress', function () {
        setTimeout(function () {                    
            $.each($(".chkProperty"), function (i, e) {
                if (nameList[i] == e.value) { //nameList is an array that contains all the selected items
                    $(this).attr("checked", true);
                }
            });
        }, 1000);
    });

Upvotes: 0

Views: 501

Answers (1)

Steven Lambert
Steven Lambert

Reputation: 5891

ng-repeat will remove the DOM and all references to it when an item is not returned from the filter. Thus, if the item was checked, it is no longer checked when it gets re-inserted into the DOM because it's a brand new DOM (not the old DOM).

To solve this issue, you need to have the data (nameList) also keep the state of the item (checked/unchecked). That way each input can see if it's checked inside the ng-repeat. To do this, just have the input use an ng-model.

plunker example

Upvotes: 1

Related Questions