ChasingTimmy
ChasingTimmy

Reputation: 103

AngularJS filtering ng-repeat by array

So i have JSON data of HVAC businesses and I want to filter them by their certification array using an HTML checkbox. The following code is a simple version of what i'm working with |filter and ng-model removed

angular.module("list",[])
	.controller("listController",[listCtrlFun])

function listCtrlFun(){
 this.businesses = [
  {
  "name": "HotCold",
  "certifications": ["Residential","Installation"]
  },{
  "name": "MegaCorp",
  "certifications": ["Commercial","Installation"]
  }];
  
}
<div  ng-app="list" ng-controller="listController as vm">
<div>
 <label>
   <input type="checkbox" />
			Residential
 </label>
  <label>
    <input type="checkbox" />
			Commercial
 </label>
  <label>
    <input type="checkbox" />
			Installation
 </label>
</div>

<div ng-repeat="business in vm.businesses">
  <p>{{business.name}}</p>
</div>
</div>

The goal is so that when someone checks Installation both businesses show up and if they check Commercial and Install only that one will show up. I am not sure how to bind the values from the checkboxes so that they can be crossed referenced against the data. I have tried something like this... this.types = {Residential: true, Commercial: true, Installation: true} here and I can get the values to change when I bind them to the checkboxes. Still i am unsure how to cross reference the true/false value with the data

Upvotes: 0

Views: 61

Answers (1)

baao
baao

Reputation: 73211

Use ng-model on the checkboxes, this will set to true if checked and false if not. Then you can simply pass a function to filter that returns true if one of the business' certification is actually checked:

$scope.filterBy = function () {
  return function(e) {
    return e.certifications.some(v => $scope.options[v]);
  }
}

$scope.options = {
  Installation: true,
  Residential: true,
  Commercial: true
}

With this html

<div>
 <label>
   <input type="checkbox" ng-model="options.Residential"/>
            Residential
 </label>
  <label>
    <input type="checkbox" ng-model="options.Commercial" />
            Commercial
 </label>
  <label>
    <input type="checkbox" ng-model="options.Installation"/>
            Installation
 </label>
</div>

<div ng-repeat="business in businesses | filter:filterBy(business)">
  <p>{{business.name}}</p>
</div>

Here's a plunkr

Upvotes: 1

Related Questions