Refreshing ng-repeat dynamically with $http without reloading the page

Just a quick heads-up, I'm new to AngularJS

In my AngularJS application, I am using the $http service to fetch data. Each row has an update button that needs to trigger a server-side method (the API is already returning data) to sync with a third-party application. I need to display the Percent Complete and Status of the running sync (both stored in the database) after the update.

How can I initiate this update sync and refresh the displayed data including the % complete?

index.html

<tbody ng-controller="synchronizationController">

        <tr ng-repeat="synchronization in synchronizations">               

            <td><a href ng-href="#/synchronizations/{{synchronization.syncID}}">{{ synchronization.syncName }}</a></td>

            <td>{{synchronization.syncType}}</td>
            <td> 
            <ng-switch on="synchronization.status">
                <div ng-switch-when="0">Idle</div>
                <div ng-switch-when="1">Running</div>
                <div ng-switch-when="2">In Queue</div>
                <div ng-switch-when="3">Failed</div>
                <div ng-switch-when="4">Complete</div>
                </ng-switch>

            <div ng-show="synchronization.status == 1" class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar"
                     aria-valuenow={{synchronization.percentComplete}} aria-valuemin="0" aria-valuemax="100" style="width:auto">{{synchronization.percentComplete}}

                </div>

            <td>{{ synchronization.startTime | date:'medium' }}</td>
            <td>{{ synchronization.endTime | date:'medium'}}</td>


            <td ng-controller="synchronizationUpdate"><button class="btn btn-default" ng-click="updateData(synchronization.syncID, $index)">Update</button></td>
            <td ng-controller="synchronizationUpdate"><button class="btn btn-default" ng-really-click="fullSync(synchronization.syncID)" ng-confirm-click="Full Sync will erase all data. Are you sure?">Full</button></td>

        </tr>
    </tbody>

controller

angular.module('SynchronizationsApp').controller("synchronizationUpdate", function (
$scope, synchronizationFactory) {

     $scope.updateData = function (syncId,index) {

            synchronizationFactory.initiateUpdateSynchronization(syncId, 'Update').success(function (response) {
                console.log("Running Update Sync");
                console.log(response);
                $scope.synchronizations[index] = response.data;

            }).error(function (error) {
                console.log("Failed to run Update!" + error);
            });     
};

factory

angular.module('SynchronizationsApp').factory('synchronizationFactory', function($http, $q, $timeout){

        var exposedAPI = {
            getSynchronization: getSynchronization,
            getSynchronizations: getSynchronizations,
            initiateUpdateSynchronization: initiateUpdateSynchronization
        };

        return exposedAPI;

        function get(url) {

            return $http.get(url).success(function (data) {

                    }).error(function (msg, code) {

                        console.log(msg, code);

                    });
        }

            function getSynchronizations(){
                return get('/api/synchronizations');
            }

            function getSynchronization(syncId){
                return get('/api/synchronizations' + '/' + syncId);
            }

            function initiateUpdateSynchronization(syncId, syncType) {

                return get('dosync' + '/' + syncId + '/' + syncType);
            }

    });

Answer №1

Instead of overriding your tables in the handler and losing all the angular magic, consider updating them instead.

$scope.tables = response;

Try changing it to something like this:

$scope.tables.length = 0;
response.forEach(function(entry) {
  $scope.tables.push(entry);
});

Below is a complete example for your code:

var app = angular.module("myApp", []);
app.controller('tableController', function($scope, $http) {
  $scope.tables = [];
  tableController();

  function tableController() {
    $http.get("tables.json").success(function(response) {
      $scope.tables.length = 0;
      response.forEach(function(entry) {
        $scope.tables.push(entry);
      });
    });
  }

  function updateData(tableId) {
    $http.get("/sync/" + tableId).success(function(response) {
      $scope.tables.length = 0;
      response.forEach(function(entry) {
        $scope.tables.push(entry);
      });
    });

  }
});

https://plnkr.co/edit/ABCDEFGHIJKLM123456?p=preview

Answer №2

If you want the update button to only update a specific item in its row, not the entire table, simply pass the $index to the update function:

   <tr ng-repeat="table in tables">
      <td>{{ table.name }}</td>
      <td>{{ table.id }}</td>
      <td>{{ table.sync_status}}</td>
      <td ng-show="table.status == In Progress">{{table.percentComplete}}
      </td>
      <td>
        <!--
        <button class="btn btn-default" ng-click="updateData(table.id)">
          Update</button>
        -->
        <!-- ADD $index -->
        <button class="btn btn-default" ng-click="updateData(table.id,$index)">
          Update</button>
      </td>
    </tr>

Then make use of that index:

  $scope.updateData = updateData;

  function updateData(tableId, index) {
    $http.get("/sync/" + tableId).success(function(response) {
      $scope.tables[index].percentComplete = response.percentComplete;
    });
  }

In this scenario, only the percentComplete column on the row associated with the individual Update button will be updated.

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

Forced line break at particular point in text

I would love to implement a line break right before the "+" character, either using css styling or through a different method. Is this task achievable? #myDiv{ width: 80% } #myP{ c ...

Darkness prevails even in the presence of light

I'm currently in the process of developing a game engine using ThreeJS, and I have encountered an issue with lighting that I need assistance with. My project involves creating a grid-based RPG where each cell consists of a 10 x 10 floor and possibly ...

Struggling to make button switch in my Spring Boot Application (e.g. from "Add to Cart" to "Remove")

My application allows users to add items to their cart, which are then persisted using Spring Data JPA and saved in a MySQL database. I am looking to change the text from "Add to Cart" to "Remove" when the button is clicked, and vice versa. I have attempt ...

Using the AJAX post method to generate a JSON object from database results and send it back to a jQuery UI Dialog

I wrote a script that loads sample images from the database based on the relevant category when the page loads. Here's a simplified version of the PHP script: <?php $category = 'granite'; $samples = 'SELECT * FROM material WHERE ma ...

What could be causing the SyntaxError with JavascriptExecutor: Unexpected identifier?

Python PythonExecutor py = (PythonExecutor) driver; Boolean ready = (Boolean)py.executeScript("the following Python code"); Python Code var ready = False; window.onload = def check_ready(): ready = True def sleep(): return new Promise(resolve = ...

data storage using sessionstorage for session management

Currently, I am managing sessions in my MEAN app by utilizing AngularJS to store user data in the browser's sessionStorage. The process consists of: User logs in through the front-end User is fetched from the back-end (node) Returned data is saved t ...

When I try to use angular.injector.invoke, I am encountering an issue

As I was diving into learning angular, I came across a fascinating blog post that explained how we can access factories/services outside of controllers using angular.injector(). Excited to try it out, I attempted to implement this approach only to be greet ...

Combine and emphasize several gridview rows into a single highlighted unit

Imagine you have a gridview that looks like this: FAMILY GROUP COLOR =============================================== | | Poodle | Blue ROW1 | DOG | German Shepherd | Red | | Pitbul ...

Hovering into Transition Time

My article card has a transition on the top attribute of the info div, which is supposed to be smooth and last for 0.3 seconds. However, the description suddenly appears during this transition. I'm trying to figure out why this is happening and how to ...

Bot on Discord engaging in a gaming session

I recently developed a Discord bot with the status of ""playing a game"" and here is the code that I implemented: bot.on('ready', () => { console.log('Client is online!'); bot.user.setActivity('osu!'); Th ...

Changing the text color and background color of a span element when a ng-click event is triggered

There are two buttons, Today and Tomorrow, each with an ng-click function. By default, the button background color is white and text color is red. When the Today button is clicked, the background color changes to blue and the text color changes to white. ...

The characteristics and functions of the THREE.TransformControls

I've been attempting to utilize transformControl in my program, but due to the lack of documentation on controls at threejs.org, I find it challenging to tap into its full potential. I'm seeking information on all the properties and methods provi ...

Leveraging react redux in conjunction with next.js

Recently, I attempted to integrate Redux into my project using the next.js starter template from here. I successfully installed the next-redux-wrapper, however, I am having trouble locating the root file in the project. I followed the tutorial provided on ...

What is the process for verifying a checkbox after it has been selected?

I simplified my code to make it easier to understand const [factor, setfactor] = useState(1); const [nullify, setNullify] = useState(1); const Price = 10; const Bonus = 15; const finalPrice = (Price * factor - Bonus) * nullify; // start ...

The setInterval function is malfunctioning

If I have the following function: function check(){ alert("Welcome"); } window.onload = check(); setInterval("check();", 5000); However, it is not working properly. Oddly enough, when I refresh the page, it works as intended. How can I resolve this i ...

Using AngularJS and Rails, the GET request is triggered instead of rendering the template with ngModal

I am currently working with Rails, the angular-rails-templates gem, Angular 1.4.8, and using . In my project structure, I keep my template files in app/assets/javascripts/templates and my Angular project in app/assets/javascripts/angular-app. The setup fo ...

When employing UI-Router, custom directives may not function properly within nested views

I was developing an angular application using phonegap, ionic, and angular. I had created a custom directive that registered an event listener for the element to activate iScroll upon loading. Initially, the directive worked perfectly when all the views we ...

Vue error: Uncaught promise rejection - RangeError: The computed value update has exceeded the maximum call stack size

My computed code snippet: computed: { display: { get() { return this.display }, set(newValue) { this.display = newValue } } }, Attempting to update the computed value from a function in ...

Getting HTML from Next.js middleware - a step-by-step guide

Is there a way to send the HTTP Status Code 410 (gone) together with a customized HTML message? I want to display the following content: <h1>Error 410</h1> <h2>Permanently deleted or Gone</h2> <p>This page is not foun ...

Euler 13: Surprising outcome when attempting to combine several String variables

I'm currently working on a challenging problem found on euler: here Large sum Problem 13 In this problem, the task is to determine the first ten digits of the total sum when adding up one-hundred 50-digit numbers. 37107287533902102798797998220837590 ...