gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:42:22 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com