ng-repeat动画完成回调

时间:2014-12-28 23:07:58

标签: javascript angularjs ng-animate

所以我有一个简单的ng-repeat和javascript中定义的输入动画。

沙箱:http://codepen.io/anri82/pen/KwgGeY

代码:

<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);
    }
  };
});

在动画完成后,如何仅将$scope.state切换为done pushing ?答案应采取棱角分明的方式,不要建议setTimeout

1 个答案:

答案 0 :(得分:2)

使用您正在进行的javascript动画方法,您需要在动画的完成回调中获取当前元素的范围。由于在更新变量之后它不在角度上下文中,因此您需要通过$scope.$apply()(或使用$timeoutscope.$evalAsync等)手动调用摘要周期。而且由于ng-repeat创建了子范围,因此元素的范围实际上具有来自父控制器范围的继承属性state,因此为了使更新能够反映在父范围上,请使用对象进行包装state属性,以便子范围和父对象具有相同的对象引用。

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