Angular - 如何根据用户输入使$ interval工作

时间:2016-08-11 18:34:49

标签: angularjs angularjs-directive

我从用户那里获取日期和时间作为输入,然后想要在标签中显示它的间隔 在该日期时间结束后,我想让标签颜色发生变化。

请指导我如何实现这一目标。

https://codepen.io/shreyag020/pen/vKvmdx

$interval(function(){
todoTime=$scope.datetime;
});

1 个答案:

答案 0 :(得分:0)

以下是如何随时间更改div的背景颜色的示例。单击开始按钮从1分钟开始倒数计时器。它从没有背景开始,一旦计时器启动它变为绿色,在时间用完之前15秒它变成橙色,当时间用完它变成红色。使用ng-classngAnimate和动画挂钩动画更改背景颜色。

angular.module('app', ['ngAnimate'])
  .controller('ctrl', function($scope, $interval) {
    var timerPromise;
  
    $scope.reset = function() {
      $scope.userTime = new Date;
      $scope.userTime.setMinutes(1);
      $scope.userTime.setSeconds(0);
      $scope.resetVisible = false;
      $scope.started = false;
    }

    $scope.start = function() {
      $scope.started = true;
      $scope.resetVisible = false;
      timerPromise = $interval(function() {
        if ($scope.userTime.getSeconds() > 0 || $scope.userTime.getMinutes() > 0) {
          $scope.userTime.setTime($scope.userTime.getTime() - 1000);
        }
      }, 1000);
    }
    
    $scope.pause = function() {
      $interval.cancel(timerPromise);
      $scope.started = false;
      $scope.resetVisible = true;
    }

    $scope.timeBackground = function() {
      if ($scope.started) {
        if ($scope.userTime.getMinutes() === 0 && $scope.userTime.getSeconds() === 0) {
          $scope.resetVisible = true;
          $interval.cancel(timerPromise);
          return 'expired';
        }
        if ($scope.userTime.getMinutes() === 0 && $scope.userTime.getSeconds() <= 15) {
          return 'warning';
        }
        return 'ok';
      }
      return 'clear';
    }

    $scope.reset();
  });
.timeDisplay {
  color: white;
  font-weight: bold;
}
.ok-add,
.ok-remove,
.warning-add,
.warning-remove,
.expired-add,
.expired-remove {
  transition: background-color 1000ms linear;
}
.warning,
.warning-add.pre-warning-add-active {
  background-color: orange;
}
.expired,
.expired-add.expired-add-active {
  background-color: red;
}
.ok,
.ok-add.ok-add-active {
  background-color: green;
}
.clear {
  background-color: none;
  color: black;
}
div {
  padding: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.3/angular-animate.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <div class="timeDisplay" ng-class="timeBackground()">
    Time remaining: {{userTime | date: 'mm:ss'}}
  </div>
  <div ng-if="!started">
    <button ng-click="start()">Start</button>
  </div>
  <div ng-if="started">
    <button ng-click="pause()">Pause</button>
  </div>
  <div ng-if="resetVisible">
    <button ng-click="reset()">Reset</button>
  </div>
</div>