如何更新倒计时?

时间:2016-07-20 11:24:29

标签: javascript html css

我想通过使用指令来创建倒计时时间,并且我还需要在时间变化时添加一些css样式,例如淡出,我的问题是在html绑定中时间没有改变但是在控制台中它正在改变

这是我的HTML

<body ng-app="myApp" ng-controller="myCtrl">
<count-down-timer count-down-time=5000></count-down-timer>
 {{userCountDownTime}}
</body>

这是我的JS代码

app.directive('countDownTimer', function () {
return {
restrict: 'E',
replace: true,
link: function (scope, elem, attr) {
  scope.userCountDownTime = attr.countDownTime;
  initiate();
  function initiate() {
    console.log("initiated")
    var myVar = setInterval(decreament, 1000);
  };

  function decreament() {
    console.log("decreament");
    scope.userCountDownTime--;
    console.log(scope.userCountDownTime);
    return;
  }
}
 }});

3 个答案:

答案 0 :(得分:1)

您需要通知angularJS某些内容已发生变化。您需要致电$scope.$apply。您可以使用$interval安全地完成此操作。

app.directive('countDownTimer', function ($interval) {
    return {
    restrict: 'E',
    replace: true,
    link: function (scope, elem, attr) {
      scope.userCountDownTime = attr.countDownTime;

      $interval(decrement, 1000);

      function decrement() {
          scope.userCountDownTime--;
      }
    }
}});

编辑:修改为使用$ interval而不是$ timeout。

答案 1 :(得分:1)

你可以看一下plunkr:

https://plnkr.co/edit/FSOtUYcoPhLEwp5paNin?p=preview

.directive('countDownTimer', function ($interval) {
return {
restrict: 'E',
replace: true,
link: function (scope, elem, attr) {
  scope.userCountDownTime = attr.countDownTime;
  initiate();
  function initiate() {
    console.log("initiated")
    var myVar = $interval(decreament, 1000);
  };

您需要添加$ interval服务,这是window.setInterval的包装器 https://docs.angularjs.org/api/ng/service/ $间隔

答案 2 :(得分:0)

所以你的指令可以用

改变
app.directive('countDownTimer', [ '$interval', function ( $interval ) {
return {
restrict: 'E',
replace: true,
link: function (scope, elem, attr) {
  scope.userCountDownTime = attr.countDownTime;
  initiate();
  function initiate() {
    console.log("initiated")
    var myVar = $interval(decreament, 1000);
  };

  function decreament() {
    console.log("decreament");
    scope.userCountDownTime--;
    console.log(scope.userCountDownTime);
    return;
  }
}
 }}]);