Search code examples
javascriptangularjsanimationfadeinfadeout

How to fade in/fade out a single model when a $scope.items is updated in Angular JS?


I have just started out with Angular JS for my web application.

I have a list of objects which are rendered using <div ng-repeat="item in items">...</div>.The $scope.items list is populated using an ajax call to the server.

My module is injected with ngAnimate as below

var myApp = angular.module('myModule',['ngAnimate','infinite-scroll']);

There is an option for the user to add/delete an item. When a user adds/deletes an item I want the corresponding model to fade In/fade Out respectively. I have followed this link to implement the effects mentioned above. However, on page load all the models in the items fade in and not just when a new item in added using $scope.items.push({item-x:item-value}). I want the fade in effect only for the newly added items.

Also when when new items are pushed to the list on scroll(infinite-scroll), the items again fade-in.

Could this be achieved using ng-class directive on the html element?

Any help on achieving this would be greatly appreciated. Thanks


Solution

  • You can disable animations globally using $animate.enabled(/* boolean */). So, if you'd like to temporarily turn off animation during the initial loading of items, you could it like so:

    $http.get('example.json').then(function(result){
        // disable animation
        $animate.enabled(false);
        $scope.itemslist = result.data
        // don't enable again until after browser renders
        $timeout(function(){ $animate.enabled(true); });
    });
    

    Demo

    Notice that $timeout is necessary for re-enabling (and must be injected into the controller) in order for this to work.

    You can use the same method for use with ngInfiniteScroll - just turn it off whenever you'd like. Just make sure that you turn it back on following the completion of the event you'd like to disable animations for.