AngularUI:在应用过滤器的情况下正确更新两个列表之间的模型

AngularUI: Correctly updating the models between two lists with a filter applied

本文关键字:两个 模型 之间 列表 应用 过滤器 情况下 AngularUI 更新      更新时间:2023-09-26

我在AngularUI中使用Sortable来管理多个可排序列表。我已经让它工作到可以轻松地在列表之间移动项目,并相应地更新其相应的模型的程度。但是,如果我包含查询过滤器,如果发生以下情况,则会遇到一些问题:

  1. 用户为不是列表的第一个条目的项目输入搜索字段。
  2. 用户将筛选结果中的第一项从一个列表移动到另一个列表。
  3. 它似乎有效,直到清除查询并显示初始列表。虽然在应用查询时似乎移动了条目,但您会注意到,在清除该条目后,未筛选数组中的第一个条目被移动。

似乎Sortable在您拖放时没有考虑过滤器。以下是相关的 HTML:

  <p>Search: <input ng-model="query" /></p>
  <div class="column-wrapper">
    <ul ui-sortable="sortableTemplates" ng-model="list1" id="sortable1" class="connectedSortable">
      <li ng-repeat="item in list1|filter:query" class="itemBox">{{item.name}}</li>
    </ul>
    <ul ui-sortable="sortableTemplates" ng-model="list2" id="sortable2" class="connectedSortable">
      <li ng-repeat="item in list2|filter:query" class="itemBox">{{item.name}}</li>
    </ul>
  </div>

以及相应的 JS:

var app = angular.module('myApp', ['ui.sortable']);
app.controller('test', function($scope) {
$scope.list1 = [
    {name: 'ABC'},
    {name: 'DEF'},
    {name: 'GHI'}
];
$scope.list2 = [
    {name: 'JKL'},
    {name: 'MNO'},
    {name: 'QRS'}
];
$scope.sortableTemplates = {
    connectWith: '.connectedSortable'
}

}(;

在这里,它运行在Plunker上。

要复制问题,您可以尝试搜索GHI,然后将GHI移动到 list2。然后,清除搜索框。 ABC是实际移动到 list2 的元素(因为它是该数组中的第一个元素(,GHI保留在列表 1 中。

有没有办法让可排序与 Angular 过滤器相处,以便在列表之间排序时保留原始索引?

(我是使用Angular和JQueryUI的新手,所以答案可能很明显。我发现了类似的问题,但似乎没有直接解决这个问题。

正如您所说,ui-sortable 是使用元素索引在列表之间移动它,以便当您移动过滤列表中的第一项时,它会移动原始列表中的第一项。解决此问题的一种方法是隐藏您不希望能够移动的项目,而不是过滤您的列表,而不是像 ng-repeat 中的过滤器那样创建一个新列表。所以在你的 HTML 中:

<li ng-repeat="item in list1" class="itemBox" ng-show="visible(item)">{{item.name}}</li>

ng-show 将根据 $scope.visible(item( 返回真还是假来显示或隐藏元素。因此,我们在控制器中创建了一个函数,如果我们想查看元素,则返回 true,即它没有被过滤掉,如果它被过滤掉,则返回 false。

$scope.visible=function(item){
  //create an array containing all of the elements in both lists
  var lists=$scope.list1.concat($scope.list2);
  // filter this list using our search term
  var filteredItems=$filter('filter')(lists, $scope.query);
  //if there are no matching items left in our list then return false
  if (filteredItems.length===0){return false;}
  //see if the current item is in the filtered list   
  if (($filter('filter')(filteredItems,item)).length===1){
     return true;
  } else {
     return false;
  }
}

我在 http://plnkr.co/edit/JCQdcP?p=preview 创建了一个 plunker