【问题标题】:Filter array with priority to name property - angularjs优先于名称属性的过滤数组 - angularjs
【发布时间】:2016-03-09 07:18:05
【问题描述】:

我想过滤掉搜索结果,同时保持名称在经理之前。

我不能通过 bcoz 使用 track 我不是在实际使用 ng repeat,而是一个指令, 这是一个快速的fiddle 代表我的问题。

假设我搜索Fahad,名称中包含Fahad 的记录应该排在第一位

下划线/loadash 的解决方案也很受欢迎。

谢谢

【问题讨论】:

  • 试试这个:if ($scope.users[i].name.toLowerCase().match($scope.searchQuery))
  • 这将使过滤器特定于名称,而它必须在整个对象上
  • 您可以编写一个按名称对数组进行排序的过滤器。并按排序显示数组项。

标签: angularjs underscore.js angularjs-filter


【解决方案1】:

如果我理解正确,您只希望“名称”与 searchQuery 匹配的用户位于匹配用户列表的顶部。您并不是真的要求对匹配的用户本身进行排序。

这里是 jsfiddle 更新来做到这一点。您会注意到我使用 angular.copy 复制了 users 数组,并在匹配发生时更新它。

function TodoCtrl($scope) {
  // Code goes here

  $scope._users = [
    {name:'Zafar', manager:'Owais',visible:true},
    {name:'Owais', manager:'Fahad',visible:true},
    {name:'Fahad', manager:'Raheel',visible:true}
  ];

  $scope.users = angular.copy($scope._users);

  $scope.update = function() {
    $scope.users = angular.copy($scope._users);
    $scope.users.forEach(function (user,i) {
      var match = false;
      ['name','manager'].forEach(function (field) {
        console.log(user);
        if ($scope.users[i][field].toLowerCase().match($scope.searchQuery)) {
          match = true;
          if (field === 'name') {
            $scope.users.splice(i,1);
            $scope.users.unshift(user);
          }
        }
      });

      if (!match) {
        $scope.users[i].visible = false;
      }
      else {
        $scope.users[i].visible = true;
      }
    });
  }
}

【讨论】:

    猜你喜欢
    • 2015-06-21
    • 2019-03-22
    • 2022-06-10
    • 2010-09-25
    • 2017-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-14
    相关资源
    最近更新 更多