1
我有一個自定義的角度過濾器,我試圖使其更通用。過濾器會查看員工集合,並根據僱傭後的月數過濾列表。我試圖讓過濾器更通用,因此我可以在其他具有日期但具有不同屬性名稱的列表上使用它(例如:過去xx個月內創建的過濾器發票)。我如何傳遞要過濾的屬性的名稱,或者如何傳遞date屬性的集合而不是整個對象?傳遞對象屬性的數組來過濾
HTML
<html ng-app="dateFilterTest">
<head>
</head>
<body ng-controller="filterController">
<select ng-model="maxLookBack">
<option value="6">6 Months</option>
<option value="12" selected="selected">1 Year</option>
<option value="24">2 Year</option>
<option value="999">All</option>
</select>
<ul>
<li ng-repeat="person in people | DateAgeFilter:maxLookBack">{{person.name}}</li>
</ul>
</body>
<script type="text/javascript" src="js/angular.min.js"></script>
<script type="text/javascript" src="js/controllers/dateFiltercontroller.js"></script>
</html>
JS
var app = angular.module('dateFilterTest', []);
app.filter('DateAgeFilter', function(){
return function(items, maxage) {
var minDate = new Date()
minDate.setMonth(minDate.getMonth() - maxage);
var result = [];
for (var i=0; i<items.length; i++) {
if (items[i].hireDate.getTime() > minDate.getTime()) {
result.push(items[i]);
}
}
return result;
};
});
app.controller('filterController', function($scope){
$scope.people = [
{'name': 'Person 1',
'hireDate': new Date('Jun 1, 2013')},
{'name': 'Person 2',
'hireDate': new Date('Aug 1, 2012')},
{'name': 'Person 3',
'hireDate': new Date('May 1, 2011')},
{'name': 'Person 4',
'hireDate': new Date('Jun 1, 2012')},
{'name': 'Person 5',
'hireDate': new Date('Mar 1, 2014')},
{'name': 'Person 6',
'hireDate': new Date('Mar 1, 2014')},
];
});
plunker:
http://plnkr.co/edit/9zOWxJdMNg5zHz7qYf7c