AngularJS ngcontroller定期重新加载数据

时间:2013-08-24 08:12:21

标签: javascript angularjs

我有一个angularJS应用程序的工作实现,它从URL获取一些链接并绘制它们。 然而,URL上的链接不断更新,我想定期更新这个$ scope.listlinks,让我们说每10秒钟。

我尝试使用setInterval但没有运气。

的Javascript

var App = angular.module('App', []);
App.controller('ListLinksCtrl', 
function get($scope, $http ) {
  $http.get('http://example_url.com/my_changing_links_json').then(
       function(res){$scope.listlinks = res.data;});
}
);

HTML

<div id="cnt1" ng-controller="ListLinksCtrl">
   <div ng-repeat="singlelink in listlinks">
        <a href="{{ singlelink.url }}"> 
           {{ singlelink.destination }} 
        </a>
   </div>
</div>

8 个答案:

答案 0 :(得分:26)

虽然jvandemo的答案会有效,但我认为它可以稍微改善一下。通过使用setInterval,它打破了Angular遵循的依赖注入约定,并使控制器的单元测试变得困难。

Angular目前不通过其内置服务支持setInterval,但您可以使用$timeout服务生成相同的功能。我将控制器更改为:

app.controller('MainCtrl', function($scope, $http, $timeout) {

  // Function to get the data
  $scope.getData = function(){
    $http.get('style.css')
      .success(function(data, status, headers, config) {

      // Your code here
      console.log('Fetched data!');
    });
  };

  // Function to replicate setInterval using $timeout service.
  $scope.intervalFunction = function(){
    $timeout(function() {
      $scope.getData();
      $scope.intervalFunction();
    }, 1000)
  };

  // Kick off the interval
  $scope.intervalFunction();

});

答案 1 :(得分:9)

2016

为此做了

$ interval

    $interval(function() {
        // your stuff          
    }, 1000);

不要忘记在控制器中注入$interval

app.controller('ExampleController', ['$scope', '$interval',function($scope, $interval) {
      $interval(function() {
            // your stuff          
      , 1000); 
}]);

Sign a launch4j executable in ant with sign4j and jsign

答案 2 :(得分:4)

您可以使用setInterval函数,但需要将逻辑封装在如下函数中:

app.controller('MainCtrl', function($scope, $http) {

  // Function to get the data
  $scope.getData = function(){
    $http.get('style.css')
      .success(function(data, status, headers, config) {

        // Your code here
        console.log('Fetched data!');
      });
  };

  // Run function every second
  setInterval($scope.getData, 1000);

});

我为你的http://plnkr.co/edit/vNCbBm45VYGzEQ7cIxjZ?p=preview

创建了一个有效的plnkr

希望有所帮助!

答案 3 :(得分:2)

这个答案建立在drew.walker的答案之上,但这样做是为了让更改的控制器不会产生多个无休止的运行刷新。它也会立即运行getData,而不是将其延迟1秒。

这取决于您使用Angular路线并在其中设置Ctrls。如果你没有,你需要另一种方法来确定这个控制器是否在范围内。

app.controller('MainCtrl', function($scope, $rootScope, $route, $timeout) {

    // Function to get the data
    $scope.getData = function() {
        ...
    };

    // Get the data immediately, interval function will run 1 second later
    $scope.getData();

    // Function to replicate setInterval using $timeout service.
    $scope.intervalFunction = function() {
        var currentCtrl = $route.current.$$route.controller;
        var currentlyRunning = $rootScope.myAppMainCtrlRefreshRunning;
        //do not run if the MainCtrl is not in scope
        //do not run if we've already got another timeout underway (in case someone jumps back and forth between
        //controllers without waiting 1 second between)
        if (currentCtrl === "MainCtrl" && !currentlyRunning) {
            $timeout(function() {
                $rootScope.myAppMainCtrlRefreshRunning = true;
                $scope.getData();
                $scope.intervalFunction();
                $rootScope.myAppMainCtrlRefreshRunning = false;
            }, 1000);
        };
    };
    // Kick off the interval
    $scope.intervalFunction();

});

答案 4 :(得分:0)

我必须改为按顺序才能让它发挥作用:

来自

$scope.intervalFunction();
$rootScope.myAppMainCtrlRefreshRunning = false;

$rootScope.myAppMainCtrlRefreshRunning = false;
$scope.intervalFunction();

否则循环只执行一次

答案 5 :(得分:0)

您可以尝试使用$ q provider实现promises / deferred。

https://docs.angularjs.org/api/ng/service/$q

答案 6 :(得分:0)

Try this it worked fine for me.

$scope.intervalFunction = function(){
     if ($location.$$absUrl === "current url") {
      $timeout(function() {
      $scope.showAllEmployeeTracking();
      $scope.intervalFunction();
      console.log("loading Interval")
    }, 10000)
    }
  };

  // Kick off the interval
  $scope.intervalFunction();

答案 7 :(得分:0)

更好的解决方案是使用Angular $ interval $ destroy 提供商 示例:

var stop=$interval(function () {
            function_call();
        }, 12000)

        $scope.stopInterval = function () {
            if (angular.isDefined(stop)) {
                $interval.cancel(stop);
                stop = undefined;
            }
        };

        $scope.$on('$destroy', function () {
            // Make sure that the interval is destroyed too
            $scope.stopInterval();
        });