AngularJS:使用动画在ng-repeater中交换两个项目 [英] AngularJS: swap two items in ng-repeater with animation

查看:119
本文介绍了AngularJS:使用动画在ng-repeater中交换两个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个项目列表,每个项目都有一个唯一的ID

I have a list of items, each has a unique id

$scope.arr = [{val:0,id:'a'},{val:1,id:'b'},{val:2,id:'c'}];

每个项目根据其$ index绝对定位

Each item is absolute positioned according to their $index

<div class="item" ng-repeat="item in arr track by item.id" 
ng-style="getAbsPos($index)" >{{item.id}}</div>

我想要的只是交换 arr [0] arr [2] 在数组中,显示此动作的移动动画。结果证明非常困难。

All I wanted is swapping arr[0] and arr[2] in the array, and display a moving animation of this action. It turns out to be very difficult.

我认为这个css会起作用,因为列表是由id跟踪的。

I assume this css would work since the list is tracked by id

.item{
    transition:all 3000ms;
}

但不知何故角度决定仅移动其中一个项目dom 并重新创建另一个(为什么?!)。因此,只有一个项目是动画的。

but somehow angular decides only moving one of items' dom and re-create the other one (why?!). As result, only one item is animated.

=问题=

是否有解决方案来解决此问题,所以这两个项目在交换时都会动画?谢谢。

Is there a solution to fix this problem, so both items will be animated when they swap? Thanks.

(必须实际交换项目在数组中的位置,因此可以通过正确的索引轻松访问它)

=请参阅Plunker演示=

http://plnkr.co/edit/5AVhz81x3ZjzQFJKM0Iw?p=preview

推荐答案

在玩完之后,我找到了一个非常hacky的解决方案确实改变了数组中的项目顺序

After playing around, I did find a very hacky solution which does change the item order in array:

= Idea =


  1. 正如Zack和其他许多建议的那样,我们会保持一个记录每个项目中的显示位置( item.x ),用它来确定dom位置

  1. As Zack and many other suggested, we keep a record of display position(item.x) in each item, use it to determine dom position

<div class="item" ng-repeat="item in arr track by item.id" 
ng-style="getAbsPos(item.x)" >{{item.id}}</div>


  • 交换时,首先重新排序数组,因为dom位置由item.x确定,不是$ index,不会触发动画;

  • when swap, reordering the array first, because dom position is determined by item.x, not $index, no animation will be triggered;

     var a= arr[0];
     var c = arr[2];
     arr[0] = c;
     arr[2] = a; 
    


  • 以异步方式交换两个项目的item.x值(使用 $ timeout ),因此angular将第2步和第3步视为两个独立的dom更改,只有第3步将触发动画。

  • swap the item.x value of the two items in async manner (using $timeout), so angular treats step 2 and 3 as two separated dom changes, and only step 3 will trigger animation.

     $timeout(function(){
         var tempX = a.x;
     a.x = c.x;
     c.x = tempX;           
     },10)   
    


  • 执行批量交换操作时,这可能会产生一些问题。但是对于用户触发的简单两项交换(我的用例),似乎工作正常。

    This may create some problems when batch swap operations are performed. But for user triggered simple two items swap (my use case), it seems works just ok.

    如果有更好的解决方案,请告诉我,谢谢。

    Let me know if there is a better solution, thanks.

    = Plunker demo =

    http://plnkr.co/edit/Vjj9qCcoqMCyuOhNYKKY?p=preview

    这篇关于AngularJS:使用动画在ng-repeater中交换两个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆