3

I have a filtered list of objects being repeated with ng-repeat with an input checkbox beside each item. When the list isn't filtered (as it is when the page is loaded) then I don't want the checkboxes checked. If the list is filtered I do want the checkboxes checked (the checkboxes form a treeview via CSS).

The checkbox has ng-checked="{{site.isChecked}}". When the list is filtered I am updating the isChecked variable on the objects within the filter javascript code, but this isn't updating the checkbox value. If the item is filtered out so it's removed from screen and then filtered back in again the updated isChecked value will come through to the screen.

The HTML is as follows:

<ul>
    <li ng-repeat="site in sites | filterSites:searchBuildings">
        <input type="checkbox" ng-checked="{{site.isChecked}}" id="item-f{{site.id}}" /><label for="item-f{{site.id}}">{{site.site}}</label>
        <ul>
            <li ng-repeat="building in site.filteredBuildings">
                <a href="#" ng-click="getBuilding(building)">{{building.address}}</a>
            </li>
        </ul>
    </li> </ul>

The JS is:

var filtered = [];
searchBuildings = searchBuildings.toLowerCase();
angular.forEach(sites, function (site) {
    var added = false;
    var siteMatch = false;
    site.isChecked = true;
    if (site.site.toLowerCase().indexOf(searchBuildings) !== -1)
        siteMatch = true;
    angular.forEach(site.buildings, function (building) {
        if (siteMatch == true || building.search.toLowerCase().indexOf(searchBuildings) !== -1) {
            if (added == false) {
                added = true;
                filtered.push(site);
                site.filteredBuildings = [];
            }
            site.filteredBuildings.push(building);
        }
    });
});
return filtered;

Sorry if the code isn't very pretty - I'm new to AngularJS and JS and still trying to work out how things link together.

Thanks

ac66
  • 49
  • 1
  • 7

1 Answers1

4

You should use ng-model there that would provide you two way binding. Checking and unchecking the value would update the value of site.isChecked

<input type="checkbox" ng-model="site.isChecked" id="item-f{{site.id}}"/>
Pankaj Parkar
  • 134,766
  • 23
  • 234
  • 299