简体   繁体   English

如何使用AngularJS过滤器格式化时间?

[英]How to format time with AngularJS filters?

I have a timer that is counting down from a value that is being set by some user. 我有一个计时器,正在从某个用户设置的值开始倒计时。 They enter some number which is being treated as minutes. 他们输入一些被视为分钟的数字。 number * 1000 * 60 to convert it into milliseconds - and from there the counter is counting down and decrements this number. 数字* 1000 * 60将其转换为毫秒 - 从那里计数器倒计时并减少此数字。

What I want to do is format this number as minutes and seconds so if the entered number is 3.5, it should be shown as 03:30. 我想要做的是将此数字格式化为分钟和秒,因此如果输入的数字是3.5,则应显示为03:30。

I've tried using the date filter which is provided by Angular but it's not in sync with the value of the timer. 我已经尝试使用Angular提供的日期过滤器,但它与计时器的值不同步。 It would decrement once and then stops. 它会减少一次然后停止。

Code: 码:

<h4 class="timer">{{ vm.timer.ticks | date: "mm:ss"}}</h4>

The background for the timer is in a service 计时器的背景是在服务中

start(duration) {
  this.ticks = duration;
  this.timer = this.$interval(() => {
    if (this.ticks === 0) return this.stop();
    this.ticks--;
  }, 1000);
}

I think it is because you are hiding "this" in your inner function. 我认为这是因为你在你的内在功能中隐藏了“这个”。 Try to rewrite it as (untested!): 尝试将其重写为(未经测试!):

start(duration) {
  var ticks = duration;
  this.timer = this.$interval(() => {
    if (ticks === 0) return this.stop();
    ticks--;
  }, 1000);
}

Ok, so... I made a terrible mistake when I was calculating the time... 好吧,所以...当我计算时间时,我犯了一个可怕的错误......

I set up $scope.$watch to watch over my variable from the service and according to that i was changing couple other variables. 我设置了$ scope。$ watch来监视来自服务的变量,并根据我正在改变其他变量。

$scope.$watch('vm.timer.ticks', value => {
  if (value <= 0) {
    vm.timer.count = 0;
    vm.timer.latest = '';
  }
  if(vm.timer.ticks > 0)  {
    seconds = vm.timer.ticks % 60;
    minutes = Math.floor(vm.timer.ticks / 60);
    filledMinutes = minutes < 10 ? "0" + minutes : minutes;
    filledSeconds = seconds < 10 ? "0" + seconds : seconds;
    vm.displayTime = filledMinutes + ':' + filledSeconds;
  } else {
    vm.displayTime = '00:00';
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM