我有一个指令,其中包含了jquery的动画功能。我希望通过缓动动画来改变特定变量的数字。问题是指令加载后,显示的是初始数字,但没有显示随动画效果而变化的数字。
我在Plunkr创建了一个类似的版本,以便于查看正在进行的操作。
如果我从其他地方触发$ apply()显示最终数字,则跳过整个动画的数字平均值。此外,在我尝试对每个步骤应用的代码中,它会抛出正在进行的操作。错误。
这个插件几乎可以满足我的需要,除了它不会在小数位上递增而且不会使用缓动。 http://sparkalow.github.io/angular-count-to/
scope.$watch('difference', function(newVal, oldVal) {
jQuery({someValue: oldVal}).animate({someValue: newVal}, {
duration: 1000,
easing:'swing',
step: function(e) {
scope.display = e.toFixed(2);
scope.$parent.$apply();
}
});
});
和..
template: function(scope, element, attrs) {
return '<h3>' +
'<i class="fa progress-arrow" ng-class="[{\'fa-caret-up\': direction_up}, {\'fa-caret-down\': direction_down}]" aria-hidden="true"></i> ' +
'{{ display }}' +
'</div>' +
'</h3>' +
'<label>{{ label }} (lbs)</label>';
答案 0 :(得分:2)
答案是将$timeout
函数与scope.$apply()
结合使用。
这里有更新的代码,实际上可以工作:
scope.$watch('difference', function(newVal, oldVal) {
jQuery({someValue: oldVal}).animate({someValue: newVal}, {
duration: 500,
easing:'swing',
step: function(e) {
$timeout(function () {
scope.$apply(function () {
scope.display = e.toFixed(2);
});
});
}
});
这里是Plunkr
答案 1 :(得分:0)
创建指令
30
使用
export class IncrementCounterDirective implements AfterViewInit {
@Input('appIncrementCounter') to: number = 0;
constructor(private elRef: ElementRef, private renderer: Renderer2) {}
ngAfterViewInit(): void {
this.counterFunc(this.to, 2000);
}
private counterFunc(end: number, duration: number = 3000) {
let range, current: number, step, timer: any;
range = end - 0;
current = end - 150;
step = Math.abs(Math.floor(duration / range));
// console.log(`step`, step);
timer = setInterval(() => {
current += 1;
this.setText(current);
if (current >= end) {
clearInterval(timer);
}
}, step);
}
setText(n: number) {
this.renderer.setProperty(this.elRef.nativeElement, 'innerText', `${n}`);
}
}