【问题标题】:AngularJS filtering ng-repeat by arrayAngularJS按数组过滤ng-repeat
【发布时间】:2018-01-28 18:00:46
【问题描述】:

所以我有 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>

目标是,当有人检查安装时,两个企业都会出现,如果他们检查商业和安装,则只有那个会出现。我不确定如何绑定复选框中的值,以便它们可以与数据交叉引用。我已经尝试过这样的事情...this.types = {Residential: true, Commercial: true, Installation: true}here,当我将它们绑定到复选框时,我可以更改这些值。我仍然不确定如何用数据交叉引用真/假值

【问题讨论】:

    标签: angularjs json object filter nested


    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-28
      • 1970-01-01
      • 2016-07-31
      • 1970-01-01
      相关资源
      最近更新 更多