【发布时间】:2014-05-25 21:21:11
【问题描述】:
更新:我能够通过更改调用 push 方法的方式来解决它。请参阅 sn-p 中的内联 cmets。谢谢你的帮助。任何关于为什么这不是一个好主意的 cmets / 想法都将受到高度赞赏。
我有一个绑定到我的 UI 的 Angular JS 数组。当我通过 UI 向它添加一个项目时,它可以正常工作,并且我的 UI 会使用新添加的项目进行更新。所以,这段代码有效...
//The HTML UI based call to addItem works and the UI updates to reflect the new data.
<table>
<tr>
<td>Status: </td>
<td><input type="text" ng-model="item.status" /></td>
</tr>
<tr>
<td>Priority Summary: </td>
<td><input type="text" ng-model="item.priority_summary" /></td>
</tr>
<tr>
<td colspan="2"><input type="Button" value="Add" ng-click="addItem(item)" /> </td>
</tr>
</table>
<div ng-repeat="item in items">
<p class="priority">{{item.priority_summary}}</p>
<p class="type">{{item.type}}</p>
</div>
这里是 JavaScript
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"
}];
$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.
//***This code (items.push(item) is not working
//and we do not get the UI updated to show the newly added item.
/*Commented - NON WORKING
item.status = "New";
item.priority_summary = "High";
$scope.items.push(item);
// $scope.$apply();
});*/
//Working Code....
$scope.items.push({
status: 'New',
priority_summary: 'H'
});
$scope.$apply();
}
//calling subscribe on controller initialization...
$scope.subscribe();
但是,我无法理解如何以编程方式添加新项目并在 UI 上查看这些更改。
本质上,代码 sn-p 中的 subscribe() 函数正在侦听外部事件,并且需要以编程方式在列表中插入项目/更新 UI,但不起作用。
我一直在寻找一段时间并尝试了来自 SO 和其他地方的各种示例,但我无法让它适用于这个看起来相当简单的案例。任何指针或指导将不胜感激。
谢谢!
【问题讨论】:
-
可以添加监听外部事件的代码吗?
-
@AnthonyChu:我添加了订阅功能。由于我对它有各种值的警报,我知道订阅正在工作。我想我搞砸了如何将数组值添加到 Angular 和两种方式绑定以确保它在 UI 上被刷新。
-
$scope.$apply();在您的代码示例中是不必要的
-
item和newitem在subscribe()内部指的是什么? -
订阅中的新项目似乎未定义
标签: javascript angularjs