所以我有一个简单的 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 Push
?答案应该是 Angular ,不建议setTimeout
。
最佳答案
使用您正在执行的 JavaScript 动画方法,您需要在动画的完成回调中掌握当前元素的范围。由于更新变量后它位于 Angular 上下文之外,因此您需要通过执行 $scope.$apply()
(或使用 $timeout
, >scope.$evalAsync
等等)。而且由于 ng-repeat 创建了一个子作用域,元素的作用域实际上会具有从父 Controller 作用域继承的属性 state
,因此为了使更新反射(reflect)在父作用域上,请使用对象包装 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
关于javascript - ng-repeat动画完成回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27681546/