【发布时间】:2014-07-15 21:41:06
【问题描述】:
我是 Angular 的新手,正在努力更新我的 Angular 数组中已在外部更改的现有项目(不是通过 Angular 驱动的 UI)。
这是用例...我的网页是通过服务器端调用填充的,我正在将数组加载到 Angular 中并显示在列表中。
现在,如果服务器上的数据发生变化并且在表中插入了新记录,我的页面的 JavaScript 会收到通知,并通过“推送”成功地将新记录插入到 Angular 数组中(参考Programmatically inserting array values in Angular JS)。
但是,当现有记录发生更改时(在服务器端/不是通过 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();
任何强调这一点的建议或示例都会很棒。谢谢!
【问题讨论】:
-
您在寻找什么?您已经收到更改通知,而且您可以推送更新的数据?
-
@hasH:我能够插入新项目,但我不确定如何更新数组中的现有项目。典型的 Angular 过滤器似乎面向 UI,而我正在尝试对数组的项目本身进行更改。这有意义吗?
-
能否获取需要更新的数据索引?
-
是的,我应该提到这一点。我收到的 JSON 中的每条记录都有一个唯一的 ID。我是像往常一样在数组中搜索,还是有一种 Angular 方法让它变得简单?
-
我认为您需要将更新的数据替换为数组中的正确数据...据我所知,这必须由您自己完成,因为查询/更新 ...是的,它可以使用 uniqueId 来完成
标签: javascript arrays angularjs