Search code examples
angularjsng-animate

What's a good way to move items in an list with AngularJS and ng-animate?


I want to be able to reorder a list, right now I have buttons on each item to move them up and down the list. I want to use ng-animate to make the items move smoothly, but I can only find the -move animation, and that apparently only works on the top element of the two that are switching places. I can't get it to look right. Here's what I have so far: Fiddle

.person-move {
    transition: all 0.5s;
    position: relative;
    height: 0;
}

.person-move.person-move-active {
    height: 26px;
    overflow: hidden;
}

I guess I'm not sure of the purpose of -move. I'm swapping the places of two people, but it only seems to affect the top one. I'd like it to look like they are being swapped. in the sample fiddle there's a checkbox to create new objects instead of moving existing ones to fire -enter and -leave, maybe I could combine the two methods:

  1. use -move for the top person (who used to be below), animating relative position upwards
  2. use -enter for the bottom person by creating a new object, animating relative position

Is there an easier or better way to do this?

Other thoughts: Something like jquery-ui's drag and drop would be nice, but I don't want to have to include it and find out if I can get it to work with AngularJS.


Solution

  • After a lot of messing around, I got it to work the way I wanted using the CSS next sibling selector, +: (Fiddle)

    .person-move {
        position: relative;
        top: 26px;
    }
    
    .person-move.person-move-active {
        transition: all 0.5s ease;
        top: 0;
    }
    
    .person-move + div {
        /* cannot have transition on this element */
        /*transition: all 1s ease;*/
        position: relative;
        top: -26px;
    }
    
    .person-move.person-move-active + div {
        transition: all 0.5s ease;
        position: relative;
        top: 0;
    }
    

    The key was to have the transition style only on the active class selectors. The examples I've seen like on yearofmoo have them on the base classes which I can't see any reason for since those are there solely to set up the initial condition for the animation I believe. Chrome doesn't like it anyway and tries to animate to the initial condition when using the sibling selector.