-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathcount-to.js
63 lines (53 loc) · 2.13 KB
/
count-to.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
var countTo = angular.module('countTo', [])
.directive('countTo', ['$timeout', function ($timeout) {
return {
replace: false,
scope: true,
link: function (scope, element, attrs) {
var e = element[0];
var num, refreshInterval, duration, steps, step, countTo, value, increment, precision;
var calculate = function () {
refreshInterval = 30;
step = 0;
scope.timoutId = null;
precision = parseInt(attrs.precision) || 0;
countTo = parseFloat(attrs.countTo) || 0;
scope.value = parseFloat(attrs.value, 10) || 0;
duration = (parseFloat(attrs.duration) * 1000) || 0;
steps = duration / refreshInterval;
increment = ((countTo - scope.value) / steps);
num = scope.value;
}
var tick = function () {
scope.timoutId = $timeout(function () {
num += increment;
step++;
if (step >= steps) {
$timeout.cancel(scope.timoutId);
num = countTo;
e.textContent = countTo.toFixed(precision);
} else {
e.textContent = num.toFixed(precision);
tick();
}
}, refreshInterval);
}
var start = function () {
if (scope.timoutId) {
$timeout.cancel(scope.timoutId);
}
calculate();
tick();
}
attrs.$observe('countTo', function (val) {
if (val) {
start();
}
});
attrs.$observe('value', function (val) {
start();
});
return true;
}
}
}]);