Monzingo Monzingo - 3 months ago 7
Javascript Question

Angular Table Refresh

I have an api that gets called on page load. The data from the api is loaded into a table via angular ng-repeat. I also have a javascript function that gets called every 10 seconds that calls the same api for the same dataset. I Would like to know how i can apply the new dataset to the table and replace the old if the dataset changes and how to visually show this change with animation. The code is below.

Table code

<body ng-app="myApp" ng-controller="ScansController">
<div class="bs-example" id="scan-table">
<table id="scansTable" class="table table-striped">
<thead>
<tr>
<th>ScanId</th>
<th>First Name</th>
<th>Last Name</th>
<th>Time Stamp</th>
</tr>
<tr ng-repeat="scan in Scans">
<td>
{{scan.scanId}}
</td>
<td>
{{scan.firstName}}
</td>
<td>
{{scan.lastName}}
</td>
<td>
{{scan.timeStamp}}
</td>
</tr>
</thead>
</table>
</div>




Javascipt interval code

<script>
window.setInterval(function () {
$.ajax({
url: 'api/scans/',
type: 'Get',
dataType: 'json',
success: function (data) {
//Something here
},
error: function () {
alert("something failed");
}
});

}, 10000);
</script>


Angular Code

var myApp = angular.module('myApp', []);

myApp.service('dataService', function ($http) {

this.getData = function () {

return $http({
method: 'GET',
url: '/api/scans/'
});
}
});

myApp.controller('ScansController', function ($scope, dataService) {
$scope.Scans = [];

dataService.getData().then(function (result) {
$scope.Scans = result.data;
console.log(result.data);
});
});

Answer

You need to stay inside the current scope.

Setting an interval on a $http call is poison. Use a $timeout inside the success callback to recursively call the next interval.

myApp.controller('ScansController', function ($scope, $timeout, dataService) {

  $scope.Scans = [];

  function fetchData(){
    dataService.getData().then(function (result) {
      $scope.Scans = result.data;
      $timeout(function(){ fetchData(); },10000);
    });   
  }

  fetchData();
});