我想根据选定的值编写过滤器。 例如,如果我选择名称选项,我可以使用"输入文本"输入所有具有相同名称的用户。是否可以使用类似的语法" filter:{serach:name}"。
`
<input type="text" data-ng-model="search" />
<select name="option">
<option value="name">name</option>
<option value="address">address</option>
<option value="email">email</option>
</select>
<table>
<thead>
<tr>
<th>name</th>
<th>address</th>
<th>Email</th>
</tr>
</thead>
<tbody>
<tr data-ng-repeat="user in usersList | filter:{option:search}">
<td><span data-ng-bind="user.name"></span></td>
<td><span data-ng-bind="user.address"></span></td>
<td><span data-ng-bind="user.email"></span></td>
</tr>
</tbody>
</table>
</div>
</div>
</div>`
答案 0 :(得分:2)
尝试这样:
<tbody>
<tr data-ng-repeat="user in usersList | filter:{name:user.name, address: user.address}">
<td><span ng-model="user.name"></span></td>
<td><span ng-model="user.address"></span></td>
</tr>
</tbody>
答案 1 :(得分:0)
也许创建一个自定义过滤器,接受您的选择选项值作为参数和项目数组,以便您可以按该选项和文本输入的值进行过滤。对你所需要的东西可能有点过分。
我糟糕的例子:
app.controller("CurrencyController", function ($scope, $http, $filter) {
$scope.option = '';//select value
$scope.search = '';//input text
$scope.usersList = [
{'name':'luis', 'id':3, 'address':'somewhere 1'},
{'name':'charles', 'id':4, 'address':'somewhere 2'},
{'name':'john', 'id':5, 'address':'somewhere 1'},
{'name':'mike', 'id':6, 'address':'somewhere 3'}
];
$scope.filterOut = function(){
//create a copy of usersList to keep original if no value for filter
$scope.usersListCopy = angular.copy($scope.usersList);
$scope.usersListCopy = $filter('aFilter')($scope.usersListCopy, $scope.search, $scope.option);
};
}).
filter('aFilter', function() {
return function(input, searchingFor, searchOnField) {
if ( searchOnField == '' || searchingFor == '' ) {
return input;
} else {
var returnItems = [];
for (var a = 0; a < input.length; a++){
//cycle thru every item key
if(input[a][searchOnField] == searchingFor){
returnItems.push(input[a]);
}
}
console.log(returnItems);
return returnItems;
}
};
});
在我的html上,我只是在表行上迭代usersListCopy。并在开始时使用ng-init调用filterOut,以便在usersListCopy上有数据。同时设置ng-change =“filterOut();”在元素上。