2017-03-02 107 views
-1

我也有一個AngularJS控制器,它看起來是這樣的:篩選表使用AngularJS

app.controller('StudentController', ['$scope', function($scope) { 
    $scope.filter: { 
     hobby: { 
     football: false, 
     tennis: false, 
     soccer: false 
    } 
    } 
    $scope.students: [ 
     { 
     name: John, 
     hobby: [soccer, football, tennis] 
     }, 
     { 
     name: James, 
     hobby: [soccer, tennis] 
     } 
    ] 
]); 

在HTML方面,我有一些複選框和學生的表格顯示錶:

<input type="checkbox" ng-model="filter.hobby.soccer"><label>Soccer</label> 
<input type="checkbox" ng-model="filter.hobby.tennis"><label>Tennis</label> 
<input type="checkbox" ng-model="filter.hobby.football"><label>Football</label> 

<table> 
    <thead> 
    <tr> 
     <th>Name</th> 
     <th>Hobbies</th> 
    </tr> 
    </thead> 
    <tbody ng-repeat="student in students"> 
    <tr ng-hide="rotation.hideRotation"> 
     <td>{{ student.name }}</td> 
     <td>{{ student.hobby.join(', ') }}</td> 
    </tr> 
    </tbody> 
</table> 

我想知道如何使用AngularJS過濾表格。例如,當我點擊複選框來過濾足球時,只有James會出現。

+1

請考慮提供[最小,完整,可驗證示例](http://stackoverflow.com/help/mcve)。這樣,SO上的志願者更有可能幫助你。 – lealceldeiro

+0

我同意@lealceldeiro +您的json不正確。 –

回答

0

首先,你的JSON是不正確,應該是:

{  
"students": [ 
     { 
      "name": "John", 
      "hobby": [ 
       {"sport": "soccer"}, 
       {"sport": "football"}, 
       {"sport": "tennis"} 
      ] 
     }, 
     { 
      "name": "James", 
      "hobby": [ 
       {"sport": "soccer"}, 
       {"sport": "tennis"} 
      ] 
     } 
    ] 
} 

,答案是由具有angular.ForEach循環:

$scope.selectedStudents = []; 
angular.ForEach(studentsArr,function(value,key){ 
    // looping on each student's hobbies 
    angular.ForEach(value.hobby,function(value2,key2){ 
    if(value2.sport == $scope.searchForSport) { 
     $scope.selectedStudents.push(value) 
    } 
    }) 
})