扩展this。是否可以将动态过滤添加到ng-repeat?
例如,我正在考虑使用动态表单,用户可以添加/删除表单元素like this。当然这意味着ng-repeat的过滤器部分需要动态添加/删除过滤器元素。
<select>
<option>Age</option>
<option>CustomerID</option>
<option>ProductID</option>
<select>
<input type="text" name="select-option-value">
<input type="submit" value="add filter">
<input type="submit" value="remove filter">
在我的ng-repeat中:
<div ng-repeat="person in persons | filter: search">{{person.name}}</div>
如果用户点击“添加过滤器”,那么我将重复这样的重复:
<div ng-repeat="person in persons | filter: search | filter: search2">{{person.name}}</div>
当用户添加/删除过滤器表单元素时,我不确定是否可以将过滤器元素附加到ng-repeat。
有什么想法吗?
答案 0 :(得分:1)
您可以在Add上为过滤器函数数组添加过滤器。然后只需在ng-repeat上添加一个通用的自定义过滤器,它将调用堆栈中的所有函数。以下只是一个指南,而不是实际代码:
var filterStack = [],
filter1 = function () {},
filter2 = function () {};
添加过滤器:
filterStack[filterType1] = filter1;
或删除过滤器:
delete filterStack[filterType1];
并在ng-repeat
上<div ng-repeat="person in persons | filter: customFilter">
function customFilter (val) {
foreach filterStack as filter
val = filter(val)
}
答案 1 :(得分:1)
您可以将控制器上的任意功能用作过滤器。因此,您可以创建一个过滤器,在输入数组上执行您需要的任何逻辑。
所以,如果你有以下观点:
<div ng-app="myApp" ng-controller="myCtrl">
<div ng-repeat="search in searches">
<input type="text" ng-model="search.text">
</div>
<button type="button" ng-click="addSearch()">Add Search</button>
<div ng-repeat="person in people | filter:matchSearches">Name: {{person.name}}</div>
</div>
您可以拥有以下控制器:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.searches = [];
$scope.addSearch = function(){
$scope.searches.push(
{"text": ""}
);
};
// Any function on the controller can be a filter. Use this to combine the
// searches however you like. Not sure the logic you want here, but
// hopefully you can adjust to suit.
$scope.matchSearches = function(item){
return $scope.searches.filter(function(search){
console.log(search);
return search.text.trim().length > 0 && (item.name.toLowerCase().indexOf(search.text.toLowerCase())>=0);
}).length > 0;
}
$scope.people = [
{"name": "Jim Smith"},
{"name": "Bob Smith"},
{"name": "John Smith"},
{"name": "Frank Smith"},
{"name": "Jim Jones"},
{"name": "John Jones"},
];
});