1

Component.HTML file:

<div>
  <table class="table table-bordered table-responsive">
  <thead>
<tr>
  <th>Company</th>
  <th>Stock Price</th>
  <th>Last Updated Time</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="list in model.myLists">
  <th>{{list.company}}</th>
  <td>{{list.stockPrice}}</td>
  <td>{{list.lastUpdateTime}}</td>
</tr>
</tbody>
</table>
</div>

This is component.js file:

(function() {
"use strict";
var module = angular.module("stockdApp");

// Global variables
var stockList = [];

function getStocks (model) {
// api gets stock values every 2 seconds and saves it to stockList variable
stockList = newList;
model.myLists = stockList;
}
function controller($http) {
 var model = this;
 model.$onInit = function() {     
        getStocks(model);            
 } 

 model.$onChanges = function (changes) {
   console.log("channges",changes);        
 };
};

module.component("stocks", {
    templateUrl: "./stock.component.html",
    controllerAs: "model",
    controller: ["$http", controller],
    bindings: {
        myLists: "<"
    }
});
}());

I have a api call which gets new data every 2 seconds and I want to update my table whenever I get the new data. I am using Angular 1.5 and not sure how to update the table.

coolgarcon
  • 31
  • 8

2 Answers2

1

When you do

stockList = newList;
model.myLists = stockList;

you are changing the reference of the initial array. What you need to do is remove the items from myList and add new ones while keeping the reference.

Something like this:

(function() {
"use strict";
var module = angular.module("stockdApp");

function getStocks ($http, model) {
    // Modify to fit your case...
    $http.get(....).then(function(newList) {
        // Empty the array and add the new items while keeping the same refernece
        model.myLists.length = 0;
        newList.forEach(function(newElment) { model.myLists.push(newElment); });
    });
}
function controller($http) {
 var model = this;
 model.myLists = [];

 model.$onInit = function() {     
        getStocks($http, model);            
 } 

 model.$onChanges = function (changes) {
   console.log("channges",changes);        
 };
};

module.component("stocks", {
    templateUrl: "./stock.component.html",
    controllerAs: "model",
    controller: ["$http", controller],
    bindings: {
        myLists: "<"
    }
});
}());
VRPF
  • 3,118
  • 1
  • 14
  • 15
1

Maybe you could use $scope.$apply()}

function getStocks (model) {
  $scope.$apply(function(){
   stockList = newList;
   model.myLists = stockList;
 });
}

That way you tell the browser that the content of the model, got updated.