ng-repeat animation complete callback

时光毁灭记忆、已成空白 提交于 2019-12-02 21:51:56

问题


So I have a simple ng-repeat with enter animation defined in javascript.

Sandbox: http://codepen.io/anri82/pen/KwgGeY

Code:

<div ng-app="myApp" ng-controller="MyController">
  {{state}}
  <ul>
     <li class="repeat-animate" ng-repeat="item in list">{{item}}</li>
  </ul>
  <button ng-click="add()">add</button>
</div>

angular.module('myApp', ['ngAnimate'])
.controller("MyController", function($scope) { 
   $scope.state ="idle";
   $scope.id=3;
   $scope.list = [1,2];
   $scope.add = function () {
     $scope.state="pushing";
     $scope.list.push($scope.id++);
     $scope.state="done pushing";
   }; 
}).animation('.repeat-animate', function () {
  return {
    enter: function (element, done) {
      element.hide().show(2000, done);
    }
  };
});

How do I switch $scope.state to done pushing only after animation is complete? Answer should be in angular way, don't suggest setTimeout.


回答1:


With the javascript animation approach you are doing, you would need to get hold of the scope of the current element within the animation's done callback. Since it is outside of angular context after updating the variable you need to manually invoke the digest cycle by doing $scope.$apply() (or use $timeout, scope.$evalAsync and so on). And also since ng-repeat creates a child scope, element's scope would actually have the inherited property state from the parent controller scope, so in-order for the update to get reflected on the parent scope, use an object to wrap state property, so that both child scope and parent has the same object reference.

angular.module('myApp', ['ngAnimate'])
.controller("MyController", function($scope) { 
  $scope.push = {state: "idle" }; 
  $scope.id=3;
  $scope.list = [1,2];
  $scope.add = function () {
    $scope.push.state="pushing";
    $scope.list.push($scope.id++);

  }; 
}).animation('.repeat-animate', function () {
  return {
    enter: function (element, done) {
     element.hide().show(2000, function(){
          var scope = element.scope(); //Get the scope
          scope.$evalAsync(function(){ //Push it to async queue
             scope.push.state="done pushing"
          }); 
      });
    }
  };
});

Demo



来源:https://stackoverflow.com/questions/27681546/ng-repeat-animation-complete-callback

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