定期重新加载数据

定期重新加载数据

本文介绍了AngularJS ngcontroller 定期重新加载数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 angularJS 应用程序的工作实现,它从 URL 获取一些链接并绘制它们.但是 URL 上的链接会不断更新,我想定期更新此 $scope.listlinks,比如说每 10 秒更新一次.

我尝试玩 setInterval ,但没有运气.

Javascript

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

HTML

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

解决方案

虽然 jvandemo 的回答会起作用,但我认为它可以稍微改进.通过使用 setInterval,它打破了 Angular 遵循的依赖注入约定,并使控制器的单元测试变得困难.

Angular 目前不通过其内置服务支持 setInterval,但您可以使用 $timeout 服务来产生相同的功能.我会把控制器改成这样:

app.controller('MainCtrl', function($scope, $http, $timeout) {//获取数据的函数$scope.getData = function(){$http.get('style.css').success(function(data, status, headers, config) {//你的代码在这里console.log('获取数据!');});};//使用 $timeout 服务复制 setInterval 的函数.$scope.intervalFunction = function(){$超时(功能(){$scope.getData();$scope.intervalFunction();}, 1000)};//开始间隔$scope.intervalFunction();});

I have this working implementation af a angularJS app which fetches some links from an URL and paint them.However the links on the URL are being updated constantly, I would like to update periodcially this $scope.listlinks, let say every 10 seconds.

I tried playing with setInterval with no luck.

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>
解决方案

While jvandemo's answer will work, I think it can be improved slightly. By using setInterval, it breaks the dependency injection convention that Angular follows and makes unit testing of the controller difficult.

Angular doesn't currently support setInterval through its built-in services, but you can use the $timeout service to produce the same functionality. I'd change the controller to this:

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

});

这篇关于AngularJS ngcontroller 定期重新加载数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 02:03