Angular js update json by interval and update view

I am trying to find a solution on the Internet to be able to update my http json http request for a set time interval and at the same time update my bindings with new data.

I saw a few examples using $ timeout, but couldn't get it working and just wanted to find out what is the best approach for this. Also, the ability to update views with new data is reset, I can’t decide, because I couldn’t fulfill the new request.

Here is my current build.

app.js, this just shows the initial selection for json.

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, status, headers, config) { // something went wrong :( }); } ]); 

HTML setup:

 <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> 
+6
source share
1 answer

I would use $timeout .

As you know the promise of returning $timeout . Therefore, when the promise is resolved, we can again call the myLoop method.

In the following example, we call http every 10 seconds.

 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, status, headers, config) { $scope.Days = data; myLoop(); }).error(function (data, status, headers, config) { // something went wrong :( }); }, function () { console.log("Timer rejected!"); }); } myLoop(); 

As a note:

When the controller is destroyed, be sure to call $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 Demo

+9
source

All Articles