gpt4 book ai didi

angularjs - 需要将 $timeout 和 $apply 与 requestAnimationFrame 一起使用

转载 作者:行者123 更新时间:2023-11-30 23:49:11 26 4
gpt4 key购买 nike

我正在尝试使用 requestAnimationFrame 创建一个带有滚动数字的 javascript 动画

为了看到动画滚动,我需要使用 $apply 来刷新 View 。这里的问题是当我开始动画时,摘要循环已经在运行所以我的 $apply 返回错误“$apply already in progress”。

我正在寻找一种解决方案,我使用 $timeout of 0 效果很好,但我想知道是否有其他解决方案可以避免使用在性能方面不太好的超时?

感谢您的帮助!

HTML代码:

<div ng-app="myApp">
<div ng-controller="myController as ctrl">
<animated-counter data-from='0' data-to='{{ctrl.limit}}'></animated-counter>
</div>
</div>

Javascript 代码:

(function(){
'use strict';

angular
.module('myApp', [])
.directive('animatedCounter', AnimatedCounter);

AnimatedCounter.$inject = ['$timeout'];

function AnimatedCounter($timeout) {
return {
restrict: 'E',
template: '<div>{{num}}%</div>',
link: function (scope, element, attrs) {
scope.num = parseInt(attrs.from);
var max = parseInt(attrs.to);

//Loop to increment the num
function animloop() {
if (scope.num >= max) { //Stop recursive when max reach
return;
}
requestAnimationFrame(animloop);
scope.$apply(function() {
scope.num += 1;
});
}

// $timeout(function() { //if I use $timeout it works perfectly
animloop();
// });
}
};
}


angular
.module('myApp')
.controller('myController', myController);

function myController() {
var vm = this;
vm.limit = 100;
}
})();

你可以在这里找到一个 CodePen

http://codepen.io/phliem/pen/ZWOjwz?editors=1011

最佳答案

如果我像 HadiJZ 所说的那样使用 $evalAsync() ,效果会很好!

只需要更换

scope.$apply(function() {
scope.num += 1;
});

scope.$evalAsync(function() {
scope.num += 1;
})

这里有一篇好文章http://www.bennadel.com/blog/2605-scope-evalasync-vs-timeout-in-angularjs.htm

关于angularjs - 需要将 $timeout 和 $apply 与 requestAnimationFrame 一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35957361/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com