AngularJS按数组

时间:2017-08-20 15:41:10

标签: angularjs json object filter nested

所以我有HVAC业务的JSON数据,我想使用HTML复选框通过他们的认证阵列过滤它们。以下代码是我使用|filterng-model删除的简单版本



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>
&#13;
&#13;
&#13;
目标是当有人检查安装时,两个企业都会出现,如果他们检查商业和安装只会出现一个。我不确定如何绑定复选框中的值,以便可以跨数据引用它们。我尝试过这样的事情...... this.types = {Residential: true, Commercial: true, Installation: true} here当我将它们绑定到复选框时,我可以更改值。我仍然不确定如何用数据

交叉引用真/假值

1 个答案:

答案 0 :(得分:1)

在复选框上使用ng-model,如果选中则设置为true,否则设置为false。然后,您可以简单地将一个函数传递给过滤器,如果实际检查了一个业务'认证,则返回true:

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

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

使用此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