我一直试图在互联网上找到一个解决方案,能够在设定的间隔时间更新我的$http json请求,同时让它用新数据更新我的绑定.
我已经看到一些使用$timeout的例子但是无法让它工作,只是想知道最好的方法是什么.由于我无法提出新请求,因此我无法解决新数据下拉后更新视图的问题.
这是我目前的构建.
var myApp = angular.module('myApp',['ngRoute']); myApp.controller('MainCtrl',['$scope','$http',function($scope,$http,$timeout) { $scope.Days = {}; $http({ method: 'GET',url: "data.json" }) .success(function(data,status,headers,config) { $scope.Days = data; }) .error(function(data,config) { // something went wrong :( }); } ]);
HTML设置:
<ul ng-controller="MainCtrl"> <li class="date" ng-repeat-start="day in Days"> <strong>>{{ day.Date }}</strong> </li> <li class="item" ng-repeat-end ng-repeat="item in day.Items"> <strong>>{{ item.Name }}</strong> </li> </ul>
解决方法
我会使用$timeout.
如您所知$timeout返回承诺.因此,当promise得到解决时,我们可以再次调用方法myLoop.
在下面的示例中,我们每隔10秒调用一次http.
var timer; function myLoop() { // When the timeout is defined,it returns a // promise object. timer = $timeout(function () { console.log("Timeout executed",Date.now()); },10000); timer.then(function () { console.log("Timer resolved!"); $http({ method: 'GET',url: "data.json" }).success(function (data,config) { $scope.Days = data; myLoop(); }).error(function (data,config) { // something went wrong :( }); },function () { console.log("Timer rejected!"); }); } myLoop();
作为旁注:
当控制器被销毁时,一定要调用$timeout.cancel(timer);
// When the DOM element is removed from the page,// AngularJS will trigger the $destroy event on // the scope. // Cancel timeout $scope.$on("$destroy",function (event) { $timeout.cancel(timer); });
演示Fiddle