1

组件.HTML 文件:

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

这是 component.js 文件:

(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: "<"
    }
});
}());

我有一个 api 调用,它每 2 秒获取一次新数据,并且我想在获取新数据时更新我的​​表。我正在使用 Angular 1.5,但不确定如何更新表格。

4

2 回答 2

1

也许你可以使用$scope.$apply() }

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

这样你就可以告诉浏览器模型的内容已经更新了。

于 2016-11-15T18:43:17.943 回答
1

当你这样做

stockList = newList;
model.myLists = stockList;

您正在更改初始数组的引用。您需要做的是从 myList 中删除项目并添加新项目,同时保留参考。

像这样的东西:

(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: "<"
    }
});
}());
于 2016-11-15T17:43:31.480 回答