如何使用多个参数过滤对象数组?

时间:2014-03-24 09:25:22

标签: angularjs filter

我有一个包含员工所有数据的员工阵列。

列表中1名员工的示例:

accountActive: false
companynr: 0
email: "aart.versendaal@technomanage.nl"
id: 100
photoURL: "http://technet/employeephoto/anonymous.jpg"
staffnr: 0
tla: "FIS"
userName: "Firstname Surname"
workPlace: "999"

使用以下代码显示搜索结果 (仅显示名称和照片)

<div class="result" ng-repeat="employee in data | limitTo:showLimit">
    <div class="result_wrapper">
        <div class="result_name">{{employee.userName}}</div>
        <div class="result_image">
            <img ng-src="{{employee.photoURL}}"/>
        </div>
    </div>
</div>

使用此login_controller

var employees; //list of all employees
$scope.data = []; //the filtered employees
$scope.showLimit = 5;

//The filter I made (no input = no results)
$scope.getData = function (query) {
    if (query.length === 0) {
        $scope.data = [];
    } else {
        $scope.data = $filter('filter')(employees, query);
    }
};

现在我想过滤员工的多个参数(例如userName和tla)。当2个参数中的一个等于查询时,它必须位于$ scope.data中(就像||)。
我想在我的getData()函数中执行此操作,以便在给出certen查询输入时可以操作一些东西。

我在考虑类似的事情:

$scope.data = $filter('filter')(employees, {'userName': query || 'tla': query});

但那不行。
有什么建议吗?

1 个答案:

答案 0 :(得分:0)

感谢Jason Goemaat向我指出了我必须走的方向

控制器:

var employees; //list of all employees
$scope.data = []; //the filtered employees
$scope.showLimit = 5;

//The filter I made (no input = no results)
$scope.getData = function (query) {
    if (query.length === 0) {
        $scope.data = [];
    } else {
        $scope.data = $filter('employeeLogin')(employees, query);
    }
};

过滤器:

app.module.filter('employeeLogin', function () {
    return function (employees, query) {
        var results = [];
        var q = query.toLowerCase();
        angular.forEach(employees, function (employee) {
            if (employee.userName.toLowerCase().indexOf(q) !== -1) {
                results.push(employee);
            } else if (employee.tla.toLowerCase().indexOf(q) !== -1) {
                results.push(employee);
            }
        });
        return results;
    };
});