Dev*_*ern 7 javascript arrays angularjs
我是Angular的新手,我正在努力更新我的Angular数组中已经外部更改的现有项目(而不是通过Angular驱动的UI).
这是用例...我的网页是通过服务器端调用填充的,我将数组加载到Angular并显示在列表中.
现在,如果服务器上的数据发生变化并且在表中插入了新记录,则会通知我的页面的JavaScript,并通过"push"成功地将新记录插入到Angular数组中(Ref.以编程方式在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>
Run Code Online (Sandbox Code Playgroud)
这是脚本......
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();
Run Code Online (Sandbox Code Playgroud)
任何强调这一点的建议或例子都会很棒.谢谢!
我假设您可以检索要更新的相应数据的索引.所以,你可以试试.
dataList.splice(index, 1);
dataList.splice(index, 0, newItem);
Run Code Online (Sandbox Code Playgroud)
Jee*_*han -1
当模型发生变化时,Angular 视图会自动更新,因此无需执行额外操作,只需在控制器中更新模型即可
$scope.data = ajaxdata // data you received from server
Run Code Online (Sandbox Code Playgroud)
在你看来
<ul>
<li ng-repeat="item in data">{{item}}</li>
</ul>
Run Code Online (Sandbox Code Playgroud)
为了更新您的数据,您应该有一些唯一的键值对(在本例中为 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
}];
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
24067 次 |
最近记录: |