优先级为 name 属性 - angularjs 的过滤器数组

Filter array with priority to name property - angularjs

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

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

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

underscore/loadash 的解决方案也很受欢迎。

谢谢

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

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

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;
      }
    });
  }
}