Refreshing JSON data in AngularJS periodically and dynamically updating the interface

I have been trying to figure out how to update my $http json request at regular intervals and simultaneously update my bindings with the new data. I've come across examples using $timeout, but I haven't been successful in implementing it. I'm looking for the best approach to achieve this. Additionally, I am struggling to find a way to update the views with the newly fetched data.

Below is my current setup:

In the app.js file, I have 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 structure:

<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>

Answer №1

To handle this situation, I suggest using the $timeout function.

You may already know that the $timeout function returns a promise. This means that when the promise is resolved, we can then call the myLoop method again.

In the code example below, we are making an HTTP request every 10 seconds:

var timer;

function myLoop() {
    // Calling $timeout sets up 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();

Additional information:

Remember to cancel the timer using $timeout.cancel( timer ); when the controller is destroyed.

// 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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Obtaining the id in JavaScript from PHP to display information

This is the code I've written: <textarea id="summernote<?php echo $u->id ?>" name="isi" placeholder="Write here" style="width: 100%; height: 100px !important; font-size: 14px; line-height: 18px; border: ...

What is the best way to enable a DOM element's height to be resized?

I have a widget displayed in the corner of my browser that I would like to make resizable by dragging the header upwards to increase its height. The widget's position remains fixed with its bottom, left, and right properties unchanged, but I need the ...

The slideUp/slideDown feature allows for the smooth sliding of all submenu elements

I am currently working on building a sidebar using HTML, CSS, and jQuery. One issue I am facing is with the slideUp/slideDown functionality not working correctly. Specifically, whenever I try to click on a submenu to close it, both open submenus disappear. ...

JavaScript's `indexOf` function can sometimes return false when it should actually return true

I'm having trouble detecting if a specific text is present within a string. Even though the text I am looking for is clearly there, my code seems to ignore it and goes straight to the else part of the statement. Here is the snippet of code causing th ...

Display a loading GIF for every HTTP request made in Angular 4

I am a beginner with Angular and I am looking for a way to display a spinner every time an HTTP request is made. My application consists of multiple components: <component-one></component-one> <component-two></component-two> <c ...

Create a fresh new scope by incorporating an object within an ng-repeat

In my model tree, I have a collection of items displayed using ng-repeat. Each item in the ng-repeat has its own controller to manage its properties. One of these properties is "selected," which is only relevant for the current session and is not stored in ...

Deleting the v-stepper-header number with Vuetify

I have been searching everywhere in an attempt to resolve this issue, but I have not been able to find a solution. Is there a way to remove the numbers from the v-stepper-header? - Using Vuetify version: 1.5.6 Current: https://i.stack.imgur.com/gLxFX.png ...

A guide on invoking a Struts 2 action with a different parameter for each row in a jQuery DataTable

Currently, I am working on a JAVAEE project that involves the use of Struts 2 and jQuery DataTable. In this project, I need to add a link with each row in the DataTable that will call an action based on the row's ID. Below is the HTML code for this s ...

What is the method for including a placeholder with sequential numbering?

When I click on the "Add String" button, it clones the first table row with an input in the table and adds it to the table. I also need to add a +1 number in the placeholder of the copied element. How can I determine the last placeholder before copying and ...

Guide on displaying the appropriate component in NextJs routes

Whenever I switch routes, I encounter an issue. While navigating between pages works fine, dynamic routes are not rendered correctly. In the routes, I have a folder called uw with a file named [table].js inside. For example, when I manually navigate to uw ...

Transmitting multiple parameters via the URL using Ajax

The issue arises with the double parameter url passing, causing an error alert to pop up. The error message displayed is: Syntax Error: Unexpected string There is a new error occurring in Firefox: SyntaxError: JSON.parse: unexpected non-whitespace cha ...

Updating a property in an object within an Angular service and accessing it in a different controller

I am currently utilizing a service to transfer variables between two controllers. However, I am encountering difficulties in modifying the value of an object property. My goal is to update this value in the first controller and then access the new value in ...

Ways to align this element in the middle

<div id="1" style="display:block"> <div class="radio"> <label><input type="radio" name="o1"> <input type="text" class="form-control" id="opt1"></label> </div> <div class="radio"> <label>< ...

Create a new array by dynamically generating a key while comparing two existing arrays

One of the features in my app involves retrieving data from an API and storing it in $scope.newz. The previous user activity is loaded from LocalStorage as bookmarkData. I am facing a challenge with comparing the contentId values in arrays $scope.newz an ...

Issues with simple jquery and javascript: unable to add the class ".has-error" and onclick event not properly defined

Currently, I am working with jQuery version 2.1.4 and JavaScript to implement a straightforward form validation using Bootstrap. During this process, I have encountered three peculiar issues. While I am confident that my jQuery code is properly functi ...

When utilizing the Express framework, the object req.body is initially empty when collecting data from a basic

I'm encountering an issue where I receive an empty object in req.body when submitting my HTML form. This problem persists whether testing in Postman or directly submitting the form from localhost in the browser. Upon logging it in the node console, t ...

The error message "undefined is not a function" occurred in Protractor and the operation failed

I've searched through multiple posts but haven't been able to find a solution. HTML: <div class="col-xs-3" ng-repeat="post in posts track by $index"> <div class="well"> <h3 class="postTitle"> <a ui-s ...

jQuery button click event not registering

Confused by what should be a simple solution, I find myself struggling to figure it out at the moment. All I have is this button: <button id="logout" type="button">Logout</button> It's meant to trigger this jQuery code enclosed in script ...

The model fails to refresh within the controller

Take a look at the code in app.js .state('search', { url: '/search', templateUrl: 'templates/search-pages/home.html', controller: 'SearchController' }) .state('search/search-form&apos ...

Listening to events in controllers to update the view in AngularJS

Within my application, I retrieve a list of objects from the server. These objects are then displayed on a left sidebar as a list and on a map (leaflet) as markers on the same page. The markers/map are rendered through a service, while the sidebar list is ...