角度 - 通过单个ng模型过滤,但是在多个属性上?

时间:2016-07-06 21:12:34

标签: javascript angularjs

我有以下输入数据:

  $scope.postList = [{
    name: "Hello World #1",
    is_published: false,
    targeting: false
  }, {
    name: "Hello World #2",
    is_published: true,
    targeting: true
  }, {
    name: "Hello World #3",
    is_published: true,
    targeting: true
  }, {
    name: "Hello World #4",
    is_published: false,
    targeting: true
  }];

现在,我应该能够从以下选择中过滤结果(使用ng-repeat显示)。

<select ng-model="filterByCriteria">
   <option ng-value="published">Published</option>
   <option ng-value="published">Unpublished</option>
   <option ng-value="targeting">Custom Targeting</option>
   <option ng-value="public">Public</option>
</select>

如您所见,&#34;已发布/未发布&#34;与is_published属性相关,&#34;自定义定位/公开&#34;与targeting属性相关。

Plnkr http://plnkr.co/edit/Ej8qSGCUbts0RVVJspM1?p=preview

1 个答案:

答案 0 :(得分:3)

您可以这样做: 添加这个新对象

$scope.filterByCriteria = [{
    is_published: true
}, {
    is_published: false
}, {
    targeting: true
}, {
    targeting: false
}];

并在HTML中

<body ng-app="myApp">
<div ng-controller="myController">
  <div>
    Filter by:
    <select ng-model="selectedCriteria">
      <option value="0">Published</option>
      <option value="1">Unpublished</option>
      <option value="2">Custom Targeting</option>
      <option value="3">Public</option>
    </select>
  </div>
  <ul>
    <li ng-repeat="post in postList | filter: filterByCriteria[selectedCriteria]">
      {{post.name}}
    </li>
  </ul>
</div>

Here is an example