angularjs 多次倒计时

angularjs multiple countdown

我需要这样倒计时:

<div  class="countdown" countdown="1482400417">00:10:02</div>

倒计时属性是倒计时结束的时间。差异显示在 hours:minutes:secs 中,并且每秒更新一次。

当我有多个这样的倒计时时,我如何在 angularjs 中执行此操作?

我做了一点挖掘,发现了一些类似的东西,但我无法理解代码。太糟糕了 post 我找到的代码:

Travian.Directive.countdown = function(a) {
    return function(c, b, l) {
        function g() {
            if ("undefined" != typeof a.K()) {
                h = b.attr("countdown");
                var c = h - a.K();
                if (0 > c || isNaN(c)) {
                    return Travian.tick.unbind(e), e = null, b.text(
                        la(0)), !1
                }
                var g = "";
                l.showDaysLimit && c >= l.showDaysLimit ? (c = Math
                    .round(c / 86400), c == f ? g = m : (g =
                        Travian.translate("ForDays", {
                            x: c
                        }), f = c)) : g = la(c, l.countdownShort &&
                    c < l.countdownShort);
                m != g && (m = g, b.text(g))
            }
        }
        var h, e = null,
            m = "",
            f = 0;
        l.showDaysLimit && c.$on("newTranslation", function() {
            f = 0
        });
        l.$observe("countdown", function(a) {
            "undefined" != typeof a && null == e && (e =
                Travian.tick.bind(g))
        });
        b.bind("$destroy", function() {
            Travian.tick.unbind(e)
        })
    }
};



  Travian.tick = new function() {
    var a = {};
    (function B() {
      window.setTimeout(B, 100);
      var b = {}, c;
      for(c in a) {
        a.hasOwnProperty(c) && "function" === typeof a[c] && (a[c](), b[c] = a[c])
      }
      a = b
    })();
    return{bind:function(b, c) {
      "function" === typeof b && (c = b, b = na("tick"));
      c();
      a[b] = c;
      return b
    }, unbind:function(b) {
      a[b] = null
    }}
  };

不完全符合您的要求,但这应该可以帮助您入门。

您可以创建一个具有并显示倒计时值的指令。此值使用 $interval 服务每秒更新一次。

myApp.directive('countdown', function() {
    return {
        restrict: 'E',
        template: '<div>{{countdownVal}}</div>',
        scope: {
            initVal: '='
        },
        controller: function($scope, $interval) {
                $scope.countdownVal = $scope.initVal;

            $interval(function () {
                    if ($scope.countdownVal > 0) {}
                        $scope.countdownVal--;
                }
            }, 1000);
        }
    }
});

有了这个起点,您可以调整此代码以添加格式,并使此指令可用作属性而不是元素。

参见 this JSFiddle 中的具体示例。

此外,请记住,您应该在完成间隔后将其销毁。来自 the docs:

Note: Intervals created by this service must be explicitly destroyed when you are finished with them. In particular they are not automatically destroyed when a controller's scope or a directive's element are destroyed. You should take this into consideration and make sure to always cancel the interval at the appropriate moment. See the example below for more details on how and when to do this.