如何在Angular 1.5中使用单向绑定?手表的替代品



Component.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,不知道如何更新表

当你这么做的时候

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

也许你可以使用适用范围。美元()}

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

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

相关内容

  • 没有找到相关文章

最新更新