javascript - 如何在 Angular 1.5 中使用单向绑定(bind)?除了 watch 还有其他选择吗?

标签 javascript angularjs angular-components angularjs-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: "<"
    }
});
}());

关于javascript - 如何在 Angular 1.5 中使用单向绑定(bind)?除了 watch 还有其他选择吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40616211/

相关文章:

javascript - 如何在 Angular 2 组件中使用 Promise 结果?

javascript - AngularJS 模板。内部 JS 不执行

Angular 6 组件作为一个对话框( Angular Material dialogRef),同时又单独存在。是否可以?

javascript - IE8 中的表单验证问题

javascript - ES6 生成器 : input value for . next()

javascript - 如何在 AngularJs 中重置计数

javascript - 将选中的复选框存储到 AngularJS 树结构的数组中

dart - AngularDart中角度组件的错误应用程序布局组件

javascript - Angular 1.5.x 组件路由器解析 (2)

javascript - jquery/js/ajax 的回调问题