asgerhallas
asgerhallas

Reputation: 17724

How do I make something blink when a variable changes with Angular

I'm pretty new to angular and I have some css like this:

.heartbeat
{
     transition:opacity 0.5s linear;
}

.heartbeat-active
{
    opacity: 1;
}

On a regular interval a property on scope is updated. How can I make this transition run once, whenever the property changes?

I have looked at ngAnimation and addClass, but have not been able to figure out how to stich that together declaratively. If that's even possible?

Upvotes: 2

Views: 1915

Answers (2)

asgerhallas
asgerhallas

Reputation: 17724

Inspired by gnom1gnoms answer and this thread https://groups.google.com/forum/#!msg/angular/xZptsb-NYc4/rKAxJ3dQhbMJ, what I ended up doing was this:

app.directive('highlightOnChange', function() {
  return {
    link: function($scope, element, attrs) {
      attrs.$observe('highlightOnChange', function(val) {
        var el = $(element);
        el.removeClass('heartbeat');
        _.defer(function() {
          el.addClass('heartbeat')
        });
      });
    }
  };
});

That is, creating a directive observes the property. I can then use it like this:

<div highlight-on-change="{{value}}"></div>

And don't need to have a reference to the element from $scope.

Upvotes: 1

gnom1gnom
gnom1gnom

Reputation: 752

Simply watch the property that you mentioned and addClass heartbeat-active when the watch is triggered

$scope.$watch('yourProperty', function(new, old) {
  if(new != old)
     $scope.yourElement.addClass(".heartbeat-active");
});

I assume that the element you want to blink is referenced inside the scope. Second thing - you should add some initial value of opacity to the heartbeat class.

Upvotes: 0

Related Questions