Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular animation

At the moment I have this line of code right in an ng-click controller

$(".message").show(300).delay(900).hide(300);

and while it works absolutely fine I've been told that I must NEVER do animations/jQuery/DOM manipulation from within a controller. Is there another way to do this that doesn't involve a ridiculous amount of messing around?

like image 936
Tules Avatar asked Mar 05 '13 15:03

Tules


2 Answers

Write a simple directive that watches its attribute:

app.directive('animateMe', function() {
   return function(scope, element, attrs) {
      scope.$watch(attrs.animateMe, function() {
         element.show(300).delay(900).hide(300);
      })
   }
})

Put that directive on the HTML element you want to animate. Have ng-click toggle a model/scope property.

<a ng-click="animateToggle = !animateToggle">animate</a>
<div animate-me="animateToggle">...</div>

More code, yes. But now you have something reusable (and you don't need selectors).

Fiddle

In the fiddle, I added ng-hide to the div so that it doesn't appear initially.


Update:
Angular 1.1.4 now has an ngAnimate directive. Although it is not as flexible as writing your own animation directive, it will handle many scenarios. The ng-show (and ng-hide) directive supports the show and hide animation methods.

like image 175
Mark Rajcok Avatar answered Sep 18 '22 19:09

Mark Rajcok


I suggest you use the new ngAnimate directive provided in the AngularJS 1.1.4 Core.

Read more here

like image 22
Kenneth Lynne Avatar answered Sep 21 '22 19:09

Kenneth Lynne