ng-animate : Animation when model changes

前提是你 提交于 2019-11-27 12:04:23
Valentyn Shybanov

There are couple of issues in your code:

  1. NEVER do DOM manipulations in the code of controller: $(elem).animate(.. is something you should avoid. Only in directives you can manipulate with DOM element.

  2. In 1.2+ versions of AngularJS you need to reference ngAnimate module.

  3. It is better to do CSS3 animations with fallback to js-based animations.

I propose to write a directive that will track changes and add a class that will trigger the animation and then remove it:

app.directive('animateOnChange', function($animate,$timeout) {
  return function(scope, elem, attr) {
      scope.$watch(attr.animateOnChange, function(nv,ov) {
        if (nv!=ov) {
          var c = nv > ov?'change-up':'change';
          $animate.addClass(elem,c).then(function() {
            $timeout(function() {$animate.removeClass(elem,c);});
          });
        }
      });
   };
});

Working example: http://plnkr.co/edit/zs495osfSnWSvWBIn3rh?p=preview

This can be solved with a simple directive and CSS3 animations.

HTML

<span animate-on-change="someValue">{{someValue}}</span>

Directive

myModule.directive('animateOnChange', function($timeout) {
  return function(scope, element, attr) {
    scope.$watch(attr.animateOnChange, function(nv,ov) {
      if (nv!=ov) {
        element.addClass('changed');
        $timeout(function() {
          element.removeClass('changed');
        }, 1000); // Could be enhanced to take duration as a parameter
      }
    });
  };
});

CSS

[animate-on-change] {
  transition: all 1s;
  -webkit-transition: all 1s;
}
[animate-on-change].changed {
  background-color: red;
  transition: none;
  -webkit-transition: none;
}

Fiddle

Nexaddo

in Angular 1.5 u can use ngAnimateSwap built in directive.

From the docs:

ngAnimateSwap is a animation-oriented directive that allows for the container to be removed and entered in whenever the associated expression changes. A common usecase for this directive is a rotating banner or slider component which contains one image being present at a time. When the active image changes then the old image will perform a leave animation and the new element will be inserted via an enter animation.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!