这是一些选项的小提琴:http: //jsfiddle.net/jgoemat/tgKkD/1/
选项 1 - 搜索多个字段
您可以使用模型上的对象(此处为“搜索”)作为过滤器,并为 l_name 和 f_name 单独输入框。这使您不仅可以过滤其中任何一个,还可以过滤两者:
any: <input ng-model="search.$"/><br/>
l_name: <input ng-model="search.l_name"/><br/>
f_name: <input ng-model="search.f_name"/><br/>
<!-- skipping code -->
<tr ng-repeat="item in items|filter:search">
选项 2 - 使用控制器上的功能
内置过滤器可以将函数作为参数,如果应包含对象,则该函数应返回 true。此函数将要过滤的对象作为其唯一参数,如果应该包含它,则返回 true。html:
<tr ng-repeat="item in items|filter:filterFunc">
控制器功能:
$scope.filterFunc = function(obj) {
// property not specified do we want to filter all instead of skipping filter?
if (!$scope.mySelect)
return obj;
if (obj[$scope.mySelect].toLowerCase().indexOf($scope.myInput.toLowerCase()) >= 0)
return obj;
return false;
};
选项 3 - 创建自定义过滤器
此过滤器函数将整个列表作为参数并返回过滤后的列表。这确实需要您创建一个角度模块并在ng-app
标签中指定它,例如ng-app="MyApp"
Html:
<tr ng-repeat="item in items|MyFilter:mySelect:myInput">
代码:
var app = angular.module('MyApp', []);
app.filter('MyFilter', function() {
return function(list, propertyName, value) {
console.log('MyFilter(list, ', propertyName, ', ', value, ')');
// property not specified do we want to filter all instead of skipping filter?
if (!propertyName)
return list;
var newList = [];
var lower = value.toLowerCase();
angular.forEach(list, function(v) {
if (v[propertyName].toLowerCase().indexOf(lower) >= 0)
newList.push(v);
});
return newList;
}
});
选项 4:ng-show
内置filter
过滤器表达式不允许您使用任何表达式,但是ng-show
您可以像这样限制可见项:
<tr ng-show="item[mySelect].toLowerCase().indexOf(myInput.toLowerCase()) >= 0 || !mySelect" ng-repeat="item in items">
我认为选项 1 简单灵活。如果您更喜欢下拉 + 字段 UI,那么我认为选项 3 是最有用的,您可以将其重新用作其他应用程序的依赖项,如下所示:
var app = angular.module("NewApp", ["MyApp"]);
我只想将它命名为“filterByNamedProperty”之类的更好的名称。选项 2 很简单,但它与您的控制器相关联。选项 4 很乱,我不会使用它。