【发布时间】:2018-05-31 18:05:02
【问题描述】:
JSFiddle:http://jsfiddle.net/ADukg/16923/.
我正在尝试在值与特定属性匹配的列表中过滤项目。
我有一个 'shownEmployees' 数组,当一个 'Show Leavers?'选中复选框,我希望 ng-repeat 列表包含“离开者”属性为“是”的对象,否则,它应该拼接它们。如果属性为“否”,则该对象应始终包含在 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);
}
})
}
})
【问题讨论】:
-
Fiddle 中的代码存在多个问题。首先,您不能将
scope.showLeavers声明为ng-repeat的布尔值和具有相同名称的ng-change的函数。其次,您的逻辑在函数中是错误的,并且试图将项目推回源数组(创建重复项)而不是推入新的空白数组。而且没有任何理由拼接不必要的项目,因为它们不会出现在空白数组中。
标签: javascript arrays angularjs filter angular-filters