Peter Warbo
Peter Warbo

Reputation: 11710

AngularJS animate div on scope update

I'm trying to animate a div with some content whenever the $scope variable is updated. I want to give the user feedback that an update has occurred.

In my controller I update the $scope through a websocket like this:

socket.syncUpdates('item', $scope.items, function(event, item, array) {
    $scope.items = array;
});

I can't get my head around how to do this. I'm using ng-animate and animation.css

Upvotes: 3

Views: 1311

Answers (1)

mohamedrias
mohamedrias

Reputation: 18566

socket.syncUpdates('item', $scope.items, function(event, item, array) {
    $scope.items = array;
    $scope.$apply();
});

In your syncUpdates, trigger $digest cycle using $apply().

Now you can do animation in two places. Either do it inside this syncUpdates itself below the $scope.$apply() else in a separate $watch.

$scope.$watch("items", function(newValue, oldValue) {
     // your animation code here
}, true);

To animate the div, Here is one sample:

myApp.animation(".fade", function () {
  return {
    addClass: function (element, className) {
      TweenMax.to(element, 1, {opacity: 0});
    },    
    removeClass: function (element, className) {
      TweenMax.to(element, 1, {opacity: 1});
    }
  }
})

In your controller:

Inject $animate inside your controller function. Then use

    $animate.addClass(document.querySelector("selector"), "fade");

Upvotes: 3

Related Questions