using setInterval in angularjs factory

£可爱£侵袭症+ 提交于 2019-11-26 17:49:47
asgoth

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

Update

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


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

A setInterval implementation in Angular -

I've created a factory called timeFunctions, which exposes $setInterval and $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.

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

  }
]);

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

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

Latest release candidate (1.2.0 rc3) has interval support. See changelog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!