Javascript 在 angularjs 工厂中使用 setInterval

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14237070/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 16:07:38  来源:igfitidea点击:

using setInterval in angularjs factory

javascriptangularjsjavascript-framework

提问by user183123

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.

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

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

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?

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

回答by asgoth

You can use $timeoutas an interval.

您可以$timeout用作间隔。

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:

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

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

回答by BradGreens

Update

更新

Angular has implemented an $interval feature in version 1.2 - http://docs.angularjs.org/api/ng.$interval

Angular 在 1.2 版中实现了 $interval 功能 - http://docs.angularjs.org/api/ng.$interval



Legacy example below, disregard unless you're using a version older than 1.2.

下面的旧示例,除非您使用的版本早于 1.2,否则请忽略。

A setInterval implementation in Angular -

Angular 中的 setInterval 实现 -

I've created a factory called timeFunctions, which exposes $setInterval and $clearInterval.

我创建了一个名为 timeFunctions 的工厂,它公开了 $setInterval 和 $clearInterval。

Note that any time I've needed to modify scope in a factory I've passed it in. I am unsure if this meets the "Angular way" of doing things, but it works well.

请注意,任何时候我需要修改工厂中的范围时,我都会将其传入。我不确定这是否符合“Angular 方式”的做事方式,但它运行良好。

app.factory('timeFunctions', [

  "$timeout",

  function timeFunctions($timeout) {
    var _intervals = {}, _intervalUID = 1;

    return {

      $setInterval: function(operation, interval, $scope) {
        var _internalId = _intervalUID++;

        _intervals[ _internalId ] = $timeout(function intervalOperation(){
            operation( $scope || undefined );
            _intervals[ _internalId ] = $timeout(intervalOperation, interval);
        }, interval);

        return _internalId;
      },

      $clearInterval: function(id) {
        return $timeout.cancel( _intervals[ id ] );
      }
    }
  }
]);

Example Usage:

示例用法:

app.controller('myController', [

  '$scope', 'timeFunctions',

  function myController($scope, timeFunctions) {

    $scope.startFeature = function() {

      // scrollTimeout will store the unique ID for the $setInterval instance
      return $scope.scrollTimeout = timeFunctions.$setInterval(scroll, 5000, $scope);

      // Function called on interval with scope available
      function scroll($scope) {
        console.log('scroll', $scope);
        $scope.currentPage++;

      }
    },

    $scope.stopFeature = function() {
      return timeFunctions.$clearInterval( $scope.scrollTimeout );
    }

  }
]);

回答by Greg

Could you call a normal JavaScript method and then within that method wrap the Angular code with an $apply?

您能否调用一个普通的 JavaScript 方法,然后在该方法中用 $apply 包装 Angular 代码?

Example

例子

timer = setInterval('Repeater()', 50);

var Repeater = function () {
  // Get Angular scope from a known DOM element
  var scope = angular.element(document.getElementById(elem)).scope();
  scope.$apply(function () {
    scope.SomeOtherFunction();
  });
};

回答by Cemo

Latest release candidate (1.2.0 rc3) has intervalsupport. See changelog

最新的候选版本 (1.2.0 rc3) 具有间隔支持。查看变更日志