是否可以在AngularJS中有条件地打开和关闭过滤器?

ski*_*kip 2 checkbox conditional filter angularjs ng-repeat

例如,我有一张桌子,其中我向学生展示数学,科学,英语和其他科目的标记.我有一个checkbox,如果检查只会列出有学生 {{student.mathMarks + student.scienceMarks > 150}}(即学生的数学和科学标记的总和超过150).当checkbox未经检查时,它将再次显示所有学生.有没有办法将条件过滤器与给定学生联系ng-repeat起来实现这一目标?

以下是与我上面尝试解释的案例有关的代码:

<tr ng-repeat="student in students">
    <td >
        {{student.name}}
    </td>
    <td >
       {{student.mathMarks}}
    </td>
    <td >
       {{student.scienceMarks}}
    </td>
     <td >
       {{student.englishMarks}}
    </td>
</tr>

<input type="checkbox" ng-model="onlyFooStudents" />
Run Code Online (Sandbox Code Playgroud)

Cai*_*nha 6

您可以将函数作为过滤器的表达式传递.因此,在这种情况下,您所要做的就是在范围内声明一个检查标志的函数,例如:

$scope.yourCustomFilter = function(student) {
    // if flag is false, bring everybody. if not, bring only the ones that match.
    return $scope.onlyFooStudents || 
      student && student.mathMarks + student.scienceMarks > 150;
};
Run Code Online (Sandbox Code Playgroud)

在你的装订中,你将拥有ng-repeat="student in student | filter:yourCustomFilter".

如果你在其他地方使用相同的过滤器,实现它的另一种方法是创建一个自定义过滤器,你可以传递参数,在这些行中:

angular.module('appFilters', []).filter('filterStudents', function() {
   function isApproved(student) {
       return student && student.mathMarks + student.scienceMarks > 150;
   }

   return function(students, showApprovedOnly) {
     // if it is to bring everybody, we just return the original array,
     // if not, we go on and filter the students in the same way.
     return !showApprovedOnly ? students : students.filter(isApproved);

     // COMPATIBLITY: please notice that Array.prototype.filter is only available IE9+.
   };
})
Run Code Online (Sandbox Code Playgroud)

然后你绑定你ng-repeat="student in students | studentFilter:onlyFooStudents".请注意,我们将onlyFooStudents作为参数传递给过滤器,直接从作用域绑定.