2014-03-31 110 views
0

我创建了一个倒计时时钟作为大型项目的一部分。下面是服务绑定角度服务查看

'use strict'; 

angular.module('myApp') 
    .service('Countdownclock', function Countdownclock() { 
     var secondsRemaining = 0; 
     var timerProcess; 
     return { 
      //initialize the clock 
      startClock: function(minutes) { 
       secondsRemaining = minutes * 60; 
       timerProcess = setInterval(this.timer, 1000); 
      }, 
      //timer function 
      timer: function() { 
       secondsRemaining -= 1; 
       if (secondsRemaining <= 0) { 
        clearInterval(timerProcess); 
       } 
      }, 
      //get time 
      getTime: function() { 
       return secondsRemaining; 
      }, 
      //add time 
      addTime: function(seconds) { 
       secondsRemaining += seconds; 
      }, 
      //stop clock 
      stopClock: function() { 
       secondsRemaining = 0; 
       clearInterval(timerProcess); 
      } 
     }; 
    }); 

然后我调用它的从控制器,该控制器还链接到一个视图

'use strict'; 

angular.module('myApp') 
    .controller('MainCtrl', function($scope, Countdownclock) { 
     Countdownclock.startClock(1); 
     $scope.seconds = Countdownclock.getTime(); 
     $scope.$watch(Countdownclock.getTime(), function(seconds) { 
      $scope.seconds = Countdownclock.getTime(); 
     }); 
    }); 

出于某种原因,我无法弄清楚如何绑定secondsRemaining代码到$ scope.seconds。我一直在试图弄清楚这个事情大概一个小时。我在功能编程上并不完全是一个智者,所以我有一种感觉,我只是在想它是错的。

+0

你不应该使用setInterval或clearInterval方法。使用Angular等价物。抱歉在移动设备上,这限制了我的写作。请稍后再试看看 – Spock

+0

试试$ scope。$ watch('seconds',..... – Whisher

回答

2

进样$interval为您服务,并用它代替setInterval

timerProcess = $interval(this.timer, 1000); 

如果你想使用一个观察者,你可以这样注册它:

$scope.$watch(function() { return Countdownclock.getTime(); }, function (newValue, oldValue) { 
    // Might be identical when called due to initialization - Good to know for some cases 
    if (newValue !== oldValue) { 
    $scope.seconds = newValue; 
    } 
}); 

演示http://plnkr.co/edit/usUoOtWMwoDRht27joOA?p=preview

1

您可以改用其他功能:

$scope.seconds = function() { return Countdownclock.getTime() }; 

然后取出

$scope.$watch(Countdownclock.getTime(), function(seconds) { 
    $scope.seconds = Countdownclock.getTime(); 
}); 

然后,您可以用它在你的模板是这样的:

<div>{{seconds()}}</div> 

但是,首先,像斯波克说,你必须使用$间隔代替的setInterval 。