我是Angular的新手,我正在努力更新我的Angular数组中已经外部更改的现有项目(不是通过Angular驱动的UI)。
以下是用例...我的网页是通过服务器端调用填充的,我将数组加载到Angular并显示在列表中。
现在,如果服务器上的数据发生变化并且在表格中插入了新记录,我的页面JavaScript就会得到通知,并通过' push&#39成功地将新记录插入到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();
任何强调这一点的建议或例子都会很棒。谢谢!
答案 0 :(得分:9)
我假设您可以检索要更新的相应数据的索引。 所以,你可以试试。
dataList.splice(index, 1);
dataList.splice(index, 0, newItem);
答案 1 :(得分:3)
$scope.setActive = function(user) {
User.get({ id: user._id }, function(user){
user.active = true;
user.$update(function(user){
angular.forEach($scope.users, function(u, i) {
if (u._id === user._id ) {
$scope.users[i] = user;
}
});
});
});
};
答案 2 :(得分:-1)
角度视图在模型更改时自动更新,因此无需执行额外操作,只需在控制器中更新模型即可 -
$scope.data = ajaxdata // data you received from server
并在您的视图中
<ul>
<li ng-repeat="item in data">{{item}}</li>
</ul>
要更新您的数据,您应该拥有一些唯一的键值对(在本例中为u_id),如下面的代码示例
$scope.items = [{
"status": "New",
"priority_summary": "High",
"u_id" : 1
}, {
"status": "New",
"priority_summary": "High",
"u_id" : 2
}, {
"status": "New",
"priority_summary": "High",
"u_id" : 3
}, {
"status": "New",
"priority_summary": "High",
"u_id" : 4
}];