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