gpt4 book ai didi

javascript - Angular 用户界面 : Correctly updating the models between two lists with a filter applied

转载 作者:可可西里 更新时间:2023-11-01 13:12:13 25 4
gpt4 key购买 nike

我在 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'
}

});

Here it is running on Plunker.

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

有没有办法让 sortable 与 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 来显示或隐藏元素。因此,我们在我们的 Controller 中创建一个函数,如果我们想要查看元素,即它没有被过滤掉,它返回 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

关于javascript - Angular 用户界面 : Correctly updating the models between two lists with a filter applied,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19072689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com