JSFiddle:http://jsfiddle.net/ADukg/16923/。AngularJS ngRepeat - 使用复选框按单个对象属性过滤列表
我试图过滤列表中某个值与特定属性匹配的列表项。
我有'shownEmployees'数组,当'Show Leavers?'时复选框被选中,我想ng-repeat列表包含'leaver'属性为'Yes'的对象,否则它应该拼接它们。如果该属性为“否”,则该对象应始终包含在shownEmployees数组中。
我已经做了什么应该是更复杂的过滤器使用$ filter指令的多个参数,但不能找出一个简单的方法来过滤只有一个属性。
HTML:
<md-list-item ng-repeat="employee in allEmployees.shownEmployees | orderBy: sortEmployees | filter:searchEmployees">
<md-checkbox ng-change="allEmployees.showLeavers()" ng-model="allEmployees.filters.showLeavers">Show Leavers?</md-checkbox>
-
我已经试过在JS做:
app.controller('allEmployeesController', function($scope, $http, $document) {
var _this = this;
$scope.sortEmployees = '+surname'
this.shownEmployees = $scope.employees;
this.filters = {
showLeavers: false
}
console.log('Showing leavers?: ' + this.filters.showLeavers);
this.showLeavers = function() {
console.log('Showing leavers?: ' + this.filters.showLeavers);
angular.forEach($scope.employees, function(value, key) {
if (value.leaver === 'Yes') {
if (_this.filters.showLeavers) {
_this.shownEmployees.push(value);
} else {
_this.shownEmployees.splice(value);
}
}
if (value.leaver === 'No') {
_this.shownEmployees.push(value);
}
})
}
})
有在你的小提琴代码多个问题。首先,你不能将'scope.showLeavers'声明为'ng-repeat'的布尔值和具有相同名称的'ng-change'的函数。其次,你的逻辑在函数中是错误的,并且试图将项目推回源数组(创建重复项)而不是推入新的空白数组。没有任何理由拼接不必要的项目,因为这些项目不会出现在空白数组中。 – Claies