Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular js update json on interval and update the view

I've been trying to find a solution on the internet to be able to update my $http json request on a set interval time and at the same time have it update my bindings with the new data.

I've seen some examples using $timeout but haven't been able to get it working and just wanted to know what the best approach would be for this. Also being able to update the views with the new data pulled down is something I cant seem to solve as I haven't been able to make the new request.

Here is my current build.

app.js file, this just shows the initial fetch for the 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 :(
                });

        }
    ]);

The 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>
like image 869
Anks Avatar asked Apr 20 '14 11:04

Anks


1 Answers

I would use $timeout.

As you know the $timeout return promise. So when promise is resolved we can call method myLoop once more.

In following example we call http every 10 sec.

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 side note:

When 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);
});

Demo Fiddle

like image 99
Maxim Shoustin Avatar answered Oct 25 '22 02:10

Maxim Shoustin