首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用$interval更新视图

用$interval更新视图
EN

Stack Overflow用户
提问于 2015-07-25 17:02:58
回答 1查看 363关注 0票数 0

我正在构建一个简单的庞多罗定时器,还处于学习角度的早期阶段。我在使用$scope.timeView变量每秒更新视图时遇到了问题。$scope.timeView每秒钟登录一次控制台,但不记录视图。我已经尝试过注入$interval并使用apply(),但它们无法工作。我相信这对训练有素的人来说是显而易见的,我会继续寻找的。在此期间,任何帮助都将不胜感激。谢谢。

代码语言:javascript
复制
  pomodoro_timer.controller('app.controller', ['$scope', '$state', '$stateParams', function ($scope, $state, $stateParams) {

  // (function() {
  var intrvl;
  var t = 1500;
  var tDiv = $('#time');


  $scope.startTimer = function() {
    if (tDiv.hasClass("notWorking")) {
      $scope.interval(t);
      $scope.toggleClass();
    }
  };

  $scope.interval = function() {
    intrvl = setInterval(function(){
    t -= 1;
    $scope.displayTime(t)
    },1000)
  }

  $scope.displayTime = function() {
    var m = parseInt(t / 60);
    var s = parseInt(t) % 60;

    if (s < 10) {
      s = "0" + s;
    }
     $scope.timeView = m+":"+s;
  }

  $scope.stopStart = function() {
    if (tDiv.hasClass('working')) {
      $scope.toggleClass();
      clearInterval(intrvl);
      $('#QwkBreak a').text('Continue Working');        //////////////////////Should I remove jQuery?/////////////////////////
    } else if (t<1500) {          // prevents timer from starting when '#QwkBreak' is clicked, unless timer has started counting down //
      $('#QwkBreak a').text('Quick Break');
      $scope.interval();
      $scope.toggleClass();
    }
  }

  $scope.toggleClass = function() {
    tDiv.toggleClass('notWorking working');
  }

   $scope.resetTimer = function() {
    if (!tDiv.hasClass('notWorking')) {         //prevents reset button from toggling classes unless (class="working") //
      clearInterval(intrvl);
      t = 1500;
      tDiv.text("25:00");
      $scope.toggleClass();
    }
  }

// })();s
}]);




<body ng-controller="app.controller">
  <h1>Pomodoro Timer</h1>
  <div id="timeView">
    <p id="time" class="notWorking">{{ timeView }}</p>
  </div>
    <div id="controls">
      <button id="startWork"><a ng-click="startTimer()" href="#">Start Work</a></button>
      <button id="QwkBreak"><a ng-click="stopStart()" href="#">Quick Break</a></button>
      <button id="reset"><a ng-click="resetTimer()" href="#">Reset</a></button>
      <button id="5_MInBreak">5-Min Break</button>
    </div>
  </div>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-07-25 17:15:16

$interval服务,内部将管理摘要,还允许使用cancel()方法轻松摆脱计时器。

代码语言:javascript
复制
$scope.interval = function() {
    intrvl = $interval(function(){
    t -= 1;
    $scope.displayTime(t)
    },1000)
  }

现在,您还希望在作用域被破坏时从窗口中移除该间隔计时器。

代码语言:javascript
复制
$scope.$on('$destroy', function(){
    intrvl.cancel();
});

您还需要在控制器中注入$interval

还建议将所有与计时器相关的代码放在指令中。控制器中不应包含任何dom相关代码。

参考资料:$interval文档

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31628980

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档