Angular nested filters by checkbox

时间:2016-04-21 21:57:26

标签: javascript angularjs angularjs-directive angular-ngmodel angular-filters

I'm trying to build a small schedule app, which displays events happening on one of two days. Users are currently able to filter the category/topic of the events by checkboxes. Here is a demo: http://jsfiddle.net/qx3cD/201/

I want to create a nested filter, that first allows users to choose either Day 1 or Day 2, and then filters through those results by category.

Is there a way to perform a nested filter with Angular?

JS

function MyCtrl($scope) {

$scope.showAll = true;
$scope.checkChange = function() {
    for(t in $scope.categoryArray){
        if($scope.categoryArray[t].on){
            $scope.showAll = false;
            return;
        }
    }
    $scope.showAll = true;
};

   $scope.myFunc = function(a) {
   if($scope.showAll) { return true; }

   var sel = false;

    for(cat in $scope.categoryArray){
        var t = $scope.categoryArray[cat];
        console.log(t);
        if(t.on){
            if(a.category.indexOf(t.name) == -1){
                return false;
            }else{
                sel = true;
            }
        }           
    }
   return sel;
};

$scope.categoryArray = [{ name: "A", on: false}, {name:"B", on: false}, {name:"C", on: false}, {name:"D", on: false}, {name:"E", on: false},             {name:"F", on: false}, {name:"G", on: false}, {name:"H", on: false}];

$scope.sessionArray = [{
    "time": "9:00",
    "day": "day 1",
    "name": "Session One",
    "category": ["A", "B", "E", "D"]
}, {
    "time": "10:00",
    "day": "day 1",
    "name": "Session Two",
    "category": ["A", "B", "C", "D"]
}, {
    "time": "11:00",
    "day": "day 1",
    "name": "Session Three",
    "category": ["G", "F", "D", "E"]
}, {
    "time": "12:00",
    "day": "day 1",
    "name": "Intermission A",
    "category": ["A", "B", "C", "D"]
}, {
    "time": "13:00",
    "day": "day 1",
    "name": "Session Four",
    "category": ["H", "A", "E"]
}, {
    "time": "9:00",
    "day": "day 2",
    "name": "Session Five",
    "category": ["D", "E", "B", "G"]
}, {
    "time": "11:00",
    "day": "day 2",
    "name": "Session Six",
    "category": ["A", "E", "C"]
}, {
    "time": "12:00",
    "day": "day 2",
    "name": "Session Seven",
    "category": ["G", "H", "B", "C"]
}]

HTML

<li ng-repeat="cat in categoryArray">
    <label>
    <input type="checkbox" ng-model="cat.on" ng-change="checkChange()" />{{cat.name}}</label>
</li>
<hr>
<h1><strong>Category:</strong></h1>

<div ng-repeat="sessionItem in sessionArray | filter:myFunc | orderBy: 'id'" class="ng-scope">
    <h3>{{sessionItem.name}}</h3>
</div>    

DEMO

1 个答案:

答案 0 :(得分:0)

To nest another filter just add another pipe | and use the "filter" filter normally.

<div ng-repeat="sessionItem in sessionArray | filter:myFunc | filter:theFilter | orderBy: 'id'">

Check the EXAMPLE here.