javascript - 绑定(bind) Angular 服务进行查看

标签 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);
            }
        };
    });

然后我从 Controller 调用它,该 Controller 也链接到 View

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

出于某种原因,我无法弄清楚如何将 secondaryRemaining 绑定(bind)到 $scope.seconds。我花了大约一个小时试图解决这个问题。我不完全是函数式编程的奇才,所以我有一种感觉,我只是想错了。

最佳答案

$interval 注入(inject)您的服务并用它替换 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

关于javascript - 绑定(bind) Angular 服务进行查看,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22770915/

相关文章:

android - 在 android 关机时调用 onDestroy

java - 我应该绑定(bind)我的服务还是多次调用 startService ?

javascript - 添加事件类的 slider

javascript - 使用 CSS 格式化下拉列表

html - 输入以 Angular 聚焦时的焦点标签

javascript - 将表单从 Angular JS 发送到 Spring

docker - Kubernetes Pod重定向到另一个Pod中的相同端口

javascript - ajax 只加载一次

javascript - JavaScript 中最快的 MD5 实现

javascript - Angular.js 在数组创建/迭代方面比 jQuery 慢吗?