Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

javascript - AngularJS ngcontroller to be reloading data periodically

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...