Angular JS - 如何过滤数组中的多个元素?

时间:2014-05-25 11:45:56

标签: angularjs angularjs-ng-repeat

我一直在搞乱Angular.js,但我似乎无法解决这个问题,

拿下下面的笔,尝试搜索整个名称Zoey White - 过滤器工作正常,直到您开始输入白色'。我假设代码中的某些内容并没有找到一种' AND'允许您一次过滤多个数组的函数。

有没有人有任何建议可以解决这个问题?

http://codepen.io/liamtarpey/pen/jDHcB

1 个答案:

答案 0 :(得分:2)

选项1:

向用户添加fullName

$scope.users = [
    { firstName: "Camila", lastName: "Gilson", fullName: "Camila Gilson" },
    { firstName: "Zoey", lastName: "White", fullName: "Zoey White" },
];

选项2:

创建自定义搜索功能

HTML

<input ng-model="query">
<ul>
  <li ng-repeat="user in users | filter:search" >
    {{user.firstName}} {{user.lastName}}
  </li>
</ul>

Angular Ctrl

function UsersCtrl($scope) {
  // Defina query
  $scope.query = "";
  $scope.users = [
    { firstName: "Camila", lastName: "Gilson" },
    { firstName: "Zoey", lastName: "White" },
  ];

  // Custom search method
  $scope.search = function(user) {
    // Accept everything if query is empty
    if ($scope.query.length <= 0) return true;

    // Store value of query and name as lower case to make it kind of case insensitive
    var query = (""+$scope.query).toLowerCase(),
        fullName = [user.firstName, user.lastName].join(" ").toLowerCase();

    // Return true full name includes the query
    return fullName.indexOf(query) > -1;
  }
}
相关问题