在 angularjs 工厂中使用 setInterval [英] using setInterval in angularjs factory

查看:33
本文介绍了在 angularjs 工厂中使用 setInterval的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试 angularjs 文档中给出的代码(此处给出:http://jsfiddle.net/zGqB8/)它只是实现了一个时间工厂,并使用 $timeout 在每一秒后更新时间对象.

I was trying the code given in angularjs docs (given here: http://jsfiddle.net/zGqB8/) It just implements a time factory and uses $timeout to update the time object after each second.

angular.module('timeApp', [])
.factory('time', function($timeout) {
    var time = {};

    (function tick () {
        time.now = new Date().toString();
        $timeout(tick, 1000);  // how to do it using setInterval() ?
    })();

    return time;
});

我将如何使用 setInterval() 函数而不是 $timeout() 来做到这一点?我知道需要使用 scope.$apply() 来进入角度执行上下文,但这在工厂函数中如何工作?我的意思是,在控制器中,我们有一个作用域,但我们在工厂函数中没有作用域?

How would I do it using setInterval() function instead of $timeout() ? I know that one need to use scope.$apply() to enter the angular execution context but how would that work in a factory function? I mean, in a controller, we have a scope, but we don't have scope in a factory function?

推荐答案

您可以使用 $timeout 作为间隔.

You can use $timeout as an interval.

var myIntervalFunction = function() {
    cancelRefresh = $timeout(function myFunction() {
        // do something
        cancelRefresh = $timeout(myIntervalFunction, 60000);
    },60000);
};

如果视图被销毁,你可以通过监听$destroy来销毁它:

If the view is destroyed, you can destroy it with listening on $destroy:

$scope.$on('$destroy', function(e) {
        $timeout.cancel(cancelRefresh);
});

这篇关于在 angularjs 工厂中使用 setInterval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆