gpt4 book ai didi

javascript - 如何更新 Angular 数组中的现有项(已在外部更改)?

转载 作者:数据小太阳 更新时间:2023-10-29 04:33:37 27 4
gpt4 key购买 nike

我是 Angular 的新手,正在努力更新我的 Angular 数组中已在外部更改(不是通过 Angular 支持的 UI)的现有项目。

这是用例...我的网页是通过服务器端调用填充的,我正在将数组加载到 Angular 中并显示在列表中。

现在,如果服务器上的数据发生变化并且在表中插入了一条新记录,我的页面的 JavaScript 会收到通知,它会通过“推送”(引用 Programmatically inserting array values in Angular JS)成功地将一条新记录插入到 Angular 数组中。

但是,当现有记录发生更改时(在服务器端/不是通过 Angular 支持的 UI),我的页面也会收到通知。我对如何更新 Angular 数组中的正确记录一无所知? Angular 文档中是否有我遗漏的查询/更新方法?

这是我当前代码的样子...

    //The HTML UI updates to reflect the new data inserts.
<div ng-repeat="item in items">
<p class="priority">{{item.priority_summary}}</p>
<p class="type">{{item.type}}</p>
</div>

这是脚本...

    var app = angular.module('DemoApp', []);

<!-- Define controller -->
var contrl = app.controller("MainController", function ($scope) {

$scope.items = [{
"status": "New",
"priority_summary": "High"
}, {
"status": "New",
"priority_summary": "High"
}, {
"status": "New",
"priority_summary": "High"
}, {
"status": "New",
"priority_summary": "High"
}];

//The insert works fine. The question is how do I do an update if the notification is for an update, and not for insert.

$scope.addItem = function(item)
{
alert("addItem called");
$scope.items.push(item);
$scope.item = {};
}

$scope.subscribe = function(){
//Code for connecting to the endpoint...
alert("event received"); //We receive this alert, so event is received correctly.

$scope.items.push({
status: 'New',
priority_summary: 'H'
});
$scope.$apply();

}

//calling subscribe on controller initialization...
$scope.subscribe();

任何强调这一点的建议或示例都很棒。谢谢!

最佳答案

我假设您可以检索要更新的相应数据的索引。所以,你可以试试。

dataList.splice(index, 1);
dataList.splice(index, 0, newItem);

关于javascript - 如何更新 Angular 数组中的现有项(已在外部更改)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23881580/

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