我已经编辑了我的代码并将过滤移到我的控制器
<div class="tab t-1"
ng-class="{'active' : legals.activeTab === 1}"
ng-show="legals.activeTab === 1">
<br>
<label>
Sort by
<select ng-model="sortProp" class="input-medium">
<option value="price">price</option>
<option value="minutes">minutes from the nearest station</option>
</select>
</label>
<select ng-model="locationFilter" ng-options="l as l for l in found">
<option value="">all</option>
</select>
<div class="form-group">
<input type="checkbox" ng-click="findRecent()" ng-checked=""/> from the last 7 days
</div>
<div ng-repeat="value in all | filter: recentFilter | orderBy:sortProp">
<ul>
<li><strong>{{value.id}}</strong></li>
<li><strong>{{value.address}}</strong></li>
<li>city: {{value.city}}</li>
<li>postcode: {{value.postcode}}</li>
<li>price: {{value.price}}</li>
<li>num_of_beds: {{value.num_of_beds}}</li>
<li>{{value.type}}</li>
<li>{{value.minutes}}</li>
<li>{{value.added}}</li>
</ul>
</div>
</div>
我将过滤器代码移动到我的控制器并尝试在html中使用它
var isContractEndDate = function(endDate) {
var DAYS_UNTIL_END = 8;
endDate = new Date(endDate);
var lastDate = new Date(new Date().setDate(new Date().getDate() - DAYS_UNTIL_END));
if (endDate > lastDate) {
return true;
}
return false;
};
$scope.foundRecent = [];
$scope.lookup = {};
$scope.findRecent = function() {
angular.forEach($scope.all, function(value, key) {
$scope.lookup = value;
if (isContractEndDate($scope.lookup.added)) {
$scope.foundRecent.push($scope.lookup);
}
});
return $scope.foundRecent;
};
$scope.recentFilter = function(searchResults) {
if ($scope.findRecent.length > 0) {
return searchResults;
}
};
然而它也没有过滤,我认为recentFilter函数存在一些问题
答案 0 :(得分:1)
请考虑以下示例。
此filter
最初会显示您的所有items
,但点击链接会应用传递给自定义过滤器的可选参数。
<强> HTML 强>
<body ng-controller="Ctrl">
<div>
Current condition: {{ condition ? (condition | json) : 'none' }}
<input type="button" ng-click="condition = null" value="Clear">
</div>
<br>
{{ condition ? 'Filtered items' : 'All items' }}
<ul ng-repeat="item in items | myFilter:condition">
<li>
<span ng-repeat="(key, value) in item">
<a href ng-click="setCondition(key, value)">{{ value }}</a>
</span>
</li>
</ul>
</body>
<强>的JavaScript 强>
angular.module('app', [])
.controller('Ctrl', function($scope) {
$scope.items = [{
name: 'Mike',
gender: 'M',
city: 'London'
},{
name: 'Jake',
gender: 'M',
city: 'Helsinki'
},{
name: 'Cindy',
gender: 'F',
city: 'Helsinki'
}];
$scope.setCondition = function(key, value) {
$scope.condition = {
key: key,
value: value
};
};
})
.filter('myFilter', function() {
return function(data, condition) {
if (!condition) {
return data;
} else {
var filtered = [];
angular.forEach(data, function(current) {
if (current[condition.key] === condition.value) {
this.push(current);
}
}, filtered);
return filtered;
}
};
});
此处相关的plunker https://plnkr.co/edit/GHOpSw