使用离子触摸事件更新 moment.js 持续时间

Update moment.js duration with ionic touch event

我正在使用 Ionic 构建一个 iOS 应用程序。该应用程序是一个计时器,用户可以在其中指定一个时间限制,然后在该时间倒计时某个 activity。我正在尝试实现一种交互,用户将在圆圈外部拖动一个手柄,每次顺时针旋转都会将时间限制增加一分钟,反之则减少一分钟。

我有一个圆圈,您可以在其中拖动手柄,它会紧贴容器的边界。现在我正在尝试使用 Moment.js 来创建倒计时,但是我很难让定时器值在触摸事件中更新。

$scope.duration 变量是我用来跟踪计时器值的变量。我尝试使用 moment().duration() 方法指定持续时间对象并将其初始化为“00:00:00”。当我尝试在触摸手势事件中更新该值时,我无法更新计时器值。我假设我要么不明白如何在 Angular/Ionic 中正确应用更新的范围值,要么我不知道如何正确使用 Moment.js,或者很可能 - 两者都是。

这是我的模板代码:

<ion-view hide-nav-bar="true" view-title="Dashboard">
  <ion-content>
    <div class="timer">
      <div class="timer-slider"></div>
      <span class="timer-countdown">
        {{duration}}
      </span>
    </div>
  </ion-content>
</ion-view>

还有我的大控制器:

.controller('DashCtrl', function($scope, $ionicGesture) {

  var $timer = angular.element(document.getElementsByClassName('timer')[0]);
  var $timerSlider = angular.element(document.getElementsByClassName('timer-slider')[0]);
  var timerWidth = $timer[0].getBoundingClientRect().width;
  var sliderWidth = $timerSlider[0].getBoundingClientRect().width;
  var radius = timerWidth / 2;
  var deg = 0;
  var X = Math.round(radius * Math.sin(deg*Math.PI/180));
  var Y = Math.round(radius *  -Math.cos(deg*Math.PI/180));

  var counter = 0;
  $scope.duration = moment().hour(0).minute(0).second(0).format('HH : mm : ss');

  // Set timer circle aspect ratio
  $timer.css('height', timerWidth + 'px');
  $timerSlider.css({
    left: X + radius - sliderWidth / 2 + 'px',
    top: Y + radius - sliderWidth / 2 + 'px'
  });

  $ionicGesture.on('drag', function(e) {
    e.preventDefault();
    var pos = {
      x: e.gesture.touches[0].clientX,
      y: e.gesture.touches[0].clientY
    };
    var atan = Math.atan2(pos.x - radius, pos.y - radius);
    deg = -atan/(Math.PI/180) + 180; // final (0-360 positive) degrees from mouse position
    // for attraction to multiple of 90 degrees
    var distance = Math.abs( deg - ( Math.round(deg / 90) * 90 ) );
    if ( distance <= 5 || distance >= 355 )
      deg = Math.round(deg / 90) * 90;

    if(Math.floor(deg) % 6 === 0) {
      console.log(Math.floor(deg));
      $scope.duration = moment().hour(0).minute(0).second(counter++).format('HH : mm : ss');
    }

    if (deg === 360)
      deg = 0;

    X = Math.round(radius * Math.sin(deg * Math.PI / 180));
    Y = Math.round(radius *  -Math.cos(deg * Math.PI / 180));

    $timerSlider.css({
      left: X + radius - sliderWidth / 2 + 'px',
      top: Y + radius - sliderWidth / 2 + 'px'
    });
  }, $timerSlider);
})

我破解了一个 CodePen 演示。如果没有移动格式,它不能很好地跟踪拖动事件,但您可以了解我的目的。

http://codepen.io/stat30fbliss/pen/xZRrXY

这是正在运行的应用程序的屏幕截图

更新 $scope.duration、运行 $scope.$apply() 后它应该开始工作了:)