简体   繁体   中英

How do I animate a changing list in AngularJS?

I have a list of items that is fetched from the server every 5 seconds:

$timeout(function fetchList() {

      $scope.images = Image.data();

      $timeout(fetchList, 5000);

    }, 5000);

and I display them in the document with:

<img ng-repeat='image in images' ng-src="{{image.filename}}" />

each time the timeout happens I would like to fade out the items that are no longer in the list and fade in the new ones. Is it possible to do this?

The following answer is based on AngularJS 1.2.0, which differs from 1.1.5 regarding animation approach. I also used text list instead of images for simplicity.

First of all, the animations were extracted into separate module, so you'll have to load it:

<script src="http://code.angularjs.org/1.2.0/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.0/angular-animate.min.js"></script>

and add ngAnimate as module dependecy:

angular.module("app", ["ngAnimate"])

HTML markup:

<body ng-app="app">
  <ul ng-controller="list">
    <li ng-repeat="item in list track by item.id">Item {{item.id}}</li>
  </ul>
</body>

CSS, the most important part:

li {
  transition: all 0.5s;
}
li.ng-leave {
  opacity: 1; 
}
li.ng-leave-active {
  opacity: 0;  
}
li.ng-enter {
  opacity: 0;
}
li.ng-enter-active {
  opacity: 1; 
}

Working example.

ng-repeat provides three animation events to work with: enter , leave and move . Enter represents unique element being added into list, leave - being removed, and move, well, moving across it. In order to animate any of this, you just add two classes onto repeated element .ng- event (for animation start) and .ng- event -active (animation end) with desired CSS transition or animation.

Further read:

  1. ngAnimate documentation.
  2. Year of Moo article about AngularJS 1.2.0 animations

Have fun!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM