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

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

问题描述

我是想在angularjs文档中给出​​的code(这里给出: http://jsfiddle.net/zGqB8/
它只是实现了一个工厂的时间,并使用$超时更新每一秒后的时间对象。

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()函数,而不是$超时怎么会怎么办?()?
我知道,有必要使用范围。$适用()进入角执行上下文但如何将一个工厂函数工作?我的意思是,在一个控制器,我们有一个范围,但我们没有范围,一个工厂的功能?

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?

推荐答案

您可以使用 $超时作为间隔。

You can use $timeout as an interval.

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

如果该视图被破坏,可以使用监听 $灭灭它

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

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

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

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