Search code examples
javascriptangularjsng-animate

How to avoid space when using ng-leave to remove item in list


I've got several divs stacked up using ng-repeat. I'm using ng-leave to slide a div up when it is deleted. What I'd like is for all of the divs below the deleted one to slide up with the deleted one, so there is never any empty space.

As I have it, the deleted div leaves an empty space where it was during the 1s transition, then the divs underneath all immediately move up.

FIDDLE: https://jsfiddle.net/c1huchuz/6/

HTML:

<body ng-app="myApp" ng-controller="myController">

    <button ng-click="add_div()">Add Div</button><br/><br/>

    <div ng-repeat="x in random_array" class="slide">        
        {{$index}}
        <button ng-click="remove_div($index)">Delete</button>
    </div>

</body>

JS:

var app = angular.module("myApp", ['ngAnimate']);

app.controller("myController", ["$scope", function($scope) {

    $scope.random_array = []

    $scope.add_div = function() {
        var i = $scope.random_array.length
        $scope.random_array.push(i)
    }

    $scope.remove_div = function(index) {
        $scope.random_array.splice(index, 1)
    }

}]);

CSS:

div {
    position: relative;
    width: 90px;
    height: 30px;
    background-color: orange;
    border: 1px solid black;
}

.slide.ng-enter, .slide.ng-leave {
    transition: all 1s;
}

.slide.ng-enter, .slide.ng-leave.ng-leave-active {
    top: -30px;
    z-index: -1; 
}

.slide.ng-enter.ng-enter-active, .slide.ng-leave {
    top: 0px;
    z-index: -1; 
}

I tried using the following ng-move to slide up all the divs whose indices change, but it doesn't have any effect.

.slide.ng-move {
    transition: all 1s;
    top: 0px;
}

.slide.ng-move.ng-move-active {
    top: -31px;
}

Solution

  • The blank space appears because removing div has a certain height. Just set it 0 on ng-leave:

    .slide.ng-leave.ng-leave-active{
      height: 0px;
    }
    

    Here is the fiddle.