javascript - AngularJS 计数器计数到目标数

标签 javascript jquery angularjs angularjs-directive

我是 Angular 新手,想在 JQuery 中实现同样简单的函数扩展, 但使用指令(据我所知,这就是应该如何完成的)。

有人知道现成的实现吗?

我的搜索最终只找到了 JQuery 解决方案,但我不知道如何将其转换为 Angular。

这就是我需要做的:

链接到示例:http://jsfiddle.net/YWn9t/

你能帮忙吗?

函数声明:

$.fn.countTo.defaults = {
    from: 0,  // the number the element should start at
    to: 100,  // the number the element should end at
    speed: 1000,  // how long it should take to count between the target numbers
    refreshInterval: 100,  // how often the element should be updated
    decimals: 0,  // the number of decimal places to show
    onUpdate: null,  // callback method for every time the element is updated,
    onComplete: null,  // callback method for when the element finishes updating
};

使用方法:

jQuery(function($) {
        $('.timer').countTo({
            from: 50,
            to: 2500,
            speed: 5000,
            refreshInterval: 50,
            onComplete: function(value) {
                console.debug(this);
            }
        });
    });

html:

<span class="timer"></span>

取自:stackoverflow

最佳答案

嗯,它对我不起作用,我没有找到正确的实现,但它帮助我实现我自己的指令。

html:

<count-up count-to="1000" interval="1"></count-up>

指令.js

directive('countUp', ['$compile',function($compile,$timeout) {
    return {
        restrict: 'E',
        replace: false,
        scope: {
            countTo: "=countTo",
            interval: '=interval'
        },
        controller: ['$scope', '$element', '$attrs', '$timeout', function ($scope, $element, $attrs, $timeout) {
            $scope.millis = 0;
            if ($element.html().trim().length === 0) {
                $element.append($compile('<span>{{millis}}</span>')($scope));
            } else {
                $element.append($compile($element.contents())($scope));
            }

            var i=0;
            function timeloop () {
                setTimeout(function () {
                    $scope.millis++;
                    $scope.$digest();
                    i++;
                    if (i<$scope.countTo) {
                        timeloop();
                    }
                }, $scope.interval)
            }
            timeloop();
        }]
    }}])

关于javascript - AngularJS 计数器计数到目标数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21252936/

相关文章:

javascript - jQuery 可拖动/可内容编辑代码未正确响应

javascript - 刷新数据并在时间间隔后重置倒计时器

c# - 将特殊字符转换为 Html 编码字符

javascript - AngularJS:音频预览上的播放/静音按钮

javascript - 从 Controller 中触发 jQuery DOM 操作的正确方法是什么?

javascript - 如何避免将空参数传递给具有多个可选参数的函数?

javascript - 取消 XMLHttpRequest?

jquery - 如何使用 jQuery 查找多个数组中的对象

jquery - 具有可变高度的 CSS3 过渡?

javascript - angularjs 工厂未定义