What is the best way to constantly update a dynamic table in AngularJS controller every 1 second?

I am currently fetching data from an API and populating a table. I need to reload the table every 1 second, so I attempted using $timeout but encountered an error that says -

  $scope.tableParams.reload();//TypeError: Cannot read property 'reload' of undefined

Here is the code snippet:

    <div align="center">
        <div ng-app="myApp" ng-controller="customersCtrl">
            <table ng-table="tableParams">
                <tr>
                    <td>device id</td>
                    <td>device unique id</td>
                    <td>access status</td>
                    <td>current time</td>
                </tr>
                <tr>
                    <td>{{ access.id }}</td>
                    <td>{{ access.devid }}</td>
                    <td><img ng-src="{{statusValues[access.status]}}" /></td>
                    <td>{{ access.CurrentTime }}</td>
                </tr>
            </table>
        </div>
        </div>



      <script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('customersCtrl', function ($scope, $http, $timeout) {
    $http.get("http://example.com/get")
    $scope.reloadTable = function () {
        $timeout(function () {
            $scope.tableParams.settings().$scope = $scope;
            $scope.tableParams.reload();
            $scope.reloadTable();
        }, 1000)
    };
    $scope.reloadTable();
});
        </script>

Answer №1

Hey there! It looks like you're trying to update parameters using the reload method, but it appears that the reload() function is intended to work with the $route concept in order to update the URL based on parameters. Instead of using $timeout, have you considered using $interval?

I've made some modifications here for you to check out. Hopefully, this will be helpful:

var app = angular.module('myApp', []);
app.controller('customersCtrl', function ($scope, $http, $interval) {
  $scope.fn = function(){
    $http.get("https://jsonplaceholder.typicode.com/posts")
      .then(function(data){
      console.log(data.data)
        $scope.Tdata = data.data;      
    })
    }
        $interval(function () {          
          $scope.fn()
        }, 1000)      
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller="customersCtrl">
<div align="center">
        <div ng-app="myApp" ng-controller="customersCtrl">
            <table ng-table="tableParams">
                <tr>
                    <td>device id</td>
                    <td>device unique id</td>
                    <td>access status</td>
                    <td>current time</td>
                </tr>
                <tr ng-repeat="d in Tdata">
                    <td>{{ d.id }}</td>
                    <td>{{ d.title }}</td>
                    <td><img ng-src="{{}}" /></td>
                    <td>{{ d.body }}</td>
                </tr>
            </table>
        </div>
        </div>
</div>

Answer №2

To include the code line below in my script, simply insert it after initializing the tableParams object.

$scope.tableParams.settings().$scope = $scope;

Answer №3

<script type="text/javascript">
        var app = angular.module('myApp', []);
        app.controller('clientsCtrl', function ($scope, $http, $timeout, $interval) {
            retrieveData = function(){
                $http.get("http://sample.com/fetch")
                    .success(function(data) {
                        $scope.tableParams.settings().$scope = $scope;
                        $scope.refreshTable();
                    })
                    .error(function(data, status) {
                        console.error(status);
                    })
            }

            $interval(function (){
                retrieveData();
            }, 1000);
</script>

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

Improving the performance of my function

Is there a way to optimize this code for efficiency? Net-beans is flagging it for having too many lines in the functions. It also suggests creating a new function where the if statement currently resides. Can someone assist me in refactoring this code an ...

Identifying specific time intervals within an array of timestamps using jQuery

Currently, I am utilizing jQuery to manage a series of one-hour time intervals in an array. The array includes sets like: {hours[0] = '12a-1a', hours[1] = '1a-2a', hours[2] = '2a-3a', hours[3] = '2p-3p', hours[4 ...

Managing the verification of data existence in the ExpressJS service layer or controller

Working on a medium-sized website, I realized the importance of writing maintainable code with a better project structure. After stumbling upon this insightful article and some others discussing the benefits of 3-layer architecture, I found the concept qu ...

What is the mechanism behind $scope.$on activation and $destroy invocation?

Seeking an explanation on the functionality of $scope.$on and how $destroy works in two separate controllers. When switching routes, a new controller is invoked, leading to the activation of $destroy. Could someone shed some light on how $interval is in ...

Strategies for making a child div fade out when the parent div is hovered over

I have a div with the class name ordershape and inside it, there is another div called fad-res. My goal is to display the corresponding fad-res when I hover over a specific ordershape, while hiding the other divs. <div class="ordershape"> & ...

Best practice for generating date fields in jsGrid

I am a newcomer to utilizing jsGrid for creating a calendar grid, resembling the one illustrated in this image: https://i.sstatic.net/gU4V9.png The header fields have been set up as follows: var headerFields = [{ name: "name", title: "", type: " ...

Rearrange AxisX and AxisY in Lightningchart library

I am currently utilizing the lightningchart library and intend to create a ChartXY with an AreaSeries attached to it. To achieve this, I have written the following code using React and TypeScript: import { useEffect, useRef } from 'react'; impor ...

There seems to be an issue with the functionality of my addClass() event handler

$(document).ready(function() { $(".table tr:odd".addClass("highlight"); // ..... } I've got some HTML code for a table with 4 rows, and I've defined a CSS class to alter the color of the odd rows. Appreciate any help you can provide. ...

Exploring the capabilities of the Next.js router and the useRouter

import { routeHandler } from "next/client"; import { useRouteNavigator } from "next/router"; const CustomComponent = () => { const routerFromHook = useRouteNavigator(); } export default CustomComponent; Can you explain the disti ...

Unable to view images on Wordpress theme

I am currently facing an issue where some images in my asset folder are not displaying properly when I convert my HTML/CSS/JS template to Wordpress. The main problem is with the image that should show up when you first visit the website. Below is the CSS c ...

Learn the best practices for integrating the options API with the Composition API in Vue3

Using vue3 and vite2 Below is a simple code snippet. The expected behavior is that when the button is clicked, the reactive 'msg' variable should change. It works as expected in development using Vite, but after building for production (Vi ...

Navigating through different paths in an Angular application can be achieved by utilizing Angular routing to effectively nest three

Currently, I am in the process of setting up a UsersAdmin view that includes Account Registration, UserProfile class, and an Identity Role class. My framework of choice is MVC5 with default Individual Authentication, and for routing, I am utilizing ui-rout ...

Prisma generate: encountering issues resolving the dependency tree with Prisma, Postgresql, and NextJS integration

Every time I execute prisma generate, the following error is displayed: Prisma schema loaded from prisma/schema.prisma npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/ema ...

When the form receives the First and Second inputs, it returns a value of 'null'

I am currently working on a form that is meant to collect user information and store it in a database. However, I have encountered an issue where the 'fname' and 'lname' fields (the first two inputs on the form) are returning as 'n ...

What is the best way to send a 102 Processing status code in Express?

I'm in the process of configuring a new HTTP server to run a lengthy command and return the output of that shell command back to the client. Currently, I am using Express v4.17.1. However, requests from clients are consistently timing out when runnin ...

Issue encountered while utilizing Mongoose ArrayFilters for updating a nested subdocument

I am working with a Mongoose collection and need to update a nested subdocument within it. Here is the basic structure: The collection has a parent entry (Map) This entry contains an array of children (Phases) Each child has one or more grandchildren (S ...

Incorporating a secure and personalized "tracking code" feature into a PHP web application

My web application is built using vanilla PHP and MySQL, allowing registered users to create personalized profile pages. I want to implement a textarea form field in the control panel for users to input their custom tracking code (such as Facebook Pixel o ...

Senecajs responded with a result that was neither an object nor an array, displaying a Promise

Seeking guidance on incorporating promises into my Seneca modules. Firstly, there is the server.js file that exposes a route: var express = require('express'); var app = express(); var Promise = require('bluebird'); var seneca = requ ...

AngularJS: Iterating through all isolated scope directive templates and performing a click event on one of them

Here is the HTML code I am working with: <div ng-repeat="mydata in data" class="ng-scope ng-binding"> <p class="ng-binding">{{mydata.postdata}}</p> <div my-rating rating-value="rating" data-cat="post" data-id="mydata.id" >& ...

Custom password reset link for Django RestAuth

Despite trying various solutions I came across for a similar issue, none have proved successful for me. My setup involves an Angular frontend with DRF and Django Rest Auth. In order to customize the confirmation URL to direct users to my frontend, I creat ...