使用多个复选框进行过滤

时间:2016-11-30 13:04:55

标签: angularjs

我找到了如何使用一个复选框进行过滤的指南。但我想知道如何同时过滤两个复选框?我想在Size上添加过滤器。对不起,如果我不清楚。

(function () {'use strict';

angular.
  module('myApp', []).
  controller('WineCtrl', WineCtrl);

// Functions - Definitions
function WineCtrl() {
  // Variables - Private
  var self = this;

  // Variables - Public
  self.filter = {};
  self.wines = [
    {name: 'Wine A', category: 'red', size: '1'},
    {name: 'Wine B', category: 'red', size: '1'},
    {name: 'Wine C', category: 'white', size: '2'},
    {name: 'Wine D', category: 'red', size: '2'},
    {name: 'Wine E', category: 'red', size: '3'},
    {name: 'Wine F', category: 'white', size: '3'},
    {name: 'Wine G', category: 'champagne', size: '4'},
    {name: 'Wine H', category: 'champagne', size: '4'}    
  ];

  // Functions - Public
  self.filterByCategory = filterByCategory;
  self.filterBySize = filterBySize;
  self.getCategories = getCategories;

  // Functions - Definitions
  function filterByCategory(wine) {
    return self.filter[wine.category] || noFilter(self.filter);
  }
  function filterByCategory(size) {
    return self.filter[size.category] || noFilter(self.filter);
  }


  function getCategories() {
    return (self.wines || []).
      map(function (wine) { return wine.category; }).
      filter(function (cat, idx, arr) { return arr.indexOf(cat) === idx; });
  }

  function noFilter(filterObj) {
    return Object.
      keys(filterObj).
      every(function (key) { return !filterObj[key]; });
  }
}

}());

html已经完成。盒子就在那里。

<div ng-controller="WineCtrl as ctrl">
      <h3>Categories</h3>
      <div ng-repeat="category in ctrl.getCategories()">
        <label>
          <input type="checkbox" ng-model="ctrl.filter[category]" />
          {{ category }}
        </label>
        </div>
        <div ng-repeat="size in ctrl.getCategories()">
       <label>
          <input type="checkbox" ng-model="ctrl.filter[size]" />
          {{ size }}
        </label>
      </div>
      <hr />
      <h3>Available Wines</h3>
      <div ng-repeat="wine in (ctrl.wines | filter:ctrl.filterByCategory) as filteredWines">
        {{ wine.name }} <i>({{ wine.category }})</i>
      </div>
    </div>

0 个答案:

没有答案