将Angular服务绑定到视图

时间:2014-03-31 19:52:13

标签: javascript angularjs service model-binding

我创建了倒计时时钟作为更大项目的一部分。这是服务的代码

'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);
            }
        };
    });

然后我将它从控制器调用到a,该控制器也链接到视图

'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。我一直试图把这件事弄清楚大约一个小时。我不是一个功能性编程的人,所以我有一种感觉,我只是想错了。

2 个答案:

答案 0 :(得分: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 :(得分:1)

您可以改为使用功能:

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

然后删除

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

然后您可以在模板中使用它,如下所示:

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

但首先,像Spock说的那样,你必须使用$ interval而不是setInterval。