Angular Js复选框过滤器

时间:2016-01-11 05:26:10

标签: angularjs angular-filters

我想实现基于复选框的过滤器。我的餐厅有多种特色,我已经存放在一个阵列中。还有一家或多家餐馆可能有相同的专业。

我已将专业存储在不同的对象中。与id和名称一起。

现在每当我选择一个专业时,我想检查这个专业是否存在于餐厅的专业阵容中。如果是,那么回到这家餐厅。

这是我到目前为止所做的。

HTML

<div ng-app="myApp" ng-controller="myCtrl">
    <input type="text" ng-model="search_cat.name">
    <br>
    <b>Category:</b>
    <div ng-repeat="cat in cuisines">
        <b><input type="checkbox" ng-model="filterxyz[cat.id]" /> {{cat.name}}</b>
    </div>
    <hr />
    <div ng-repeat="w in filtered=(restaurants | filter:filterByCategory) ">
        {{w.name}}
    </div>
    <hr />
    Number of results: {{filtered.length}}
</div>

JS

var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope) {
    $scope.restaurants = [
        { name: "Restaurant A", specialities:['1','2','3'] },
        { name: "Restaurant B", specialities:['1','2'] },
        { name: "Restaurant C", specialities:['1','2','3','4']},
        { name: "Restaurant D", specialities:['1','2','3','4','5']},
        { name: "Restaurant E", specialities:['1']},
        { name: "Restaurant F", specialities:['3'] },
        { name: "Restaurant G", specialities:['1','4']},
        { name: "Restaurant H", specialities:['1','2','3','4'] }
    ];

    $scope.cuisines=[
            { name: "Speciality A1", id: "1"},
            { name: "Speciality A2", id: "2"},
            { name: "Speciality A3", id: "3"}, 
            { name: "Speciality A4", id: "4"}, 
            { name: "Speciality A5", id: "5"}
    ];
    $scope.filterxyz = {};

    $scope.filterByCategory = function (restaurant) {
        return $scope.filterxyz[restaurant.specialities] || noFilter($scope.filterxyz);
    };

    function noFilter(filterObj) {
        for (var key in filterObj) {
            if (filterObj[key]) {
                return false;
            }
        }
        return true;
    }            
});

1 个答案:

答案 0 :(得分:1)

通过使用函数来获取过滤器,您处于正确的轨道上。

您尝试实现的功能称为predicate功能。

  

function(value,index):谓词函数可用于写入任意过滤器。为数组的每个元素调用该函数。最终结果是谓词返回true的那些元素的数组。

请参阅工作示例here

以下示例代码:

$scope.filterByCategory = function(value, index) {
   var selectedCategories = getFilterCategories();
   if (selectedCategories.length === 0) {
       // no filter selected return true
      return true;
   }
   for (var i = 0; i < selectedCategories.length; i++) {
       if (value.specialities.indexOf(selectedCategories[i]) > -1) {
           return true;
       }
   }
   return false;
};

function getFilterCategories() {
  var selectedCategories = [];
  for (var i = 0; i < $scope.cuisines.length; i++) {
     if ($scope.cuisines[i].checked) {
        selectedCategories.push($scope.cuisines[i].id);
     }
  }
  return selectedCategories;
}

您必须更新html以将复选框绑定到选中的值,请参阅以下内容:

<div ng-repeat="cat in cuisines">
  <b><input type="checkbox" ng-model="cat.checked" /> {{cat.name}}</b>
</div>