Update: I was able to solve it by changing how I was calling the push method. Refer to the inline comments in the snippet. Thanks SO for the help. Any comments / thoughts on why this is not a good idea would be highly appreciated.
I have an Angular JS array that is bound to my UI. When I add an item to it via the UI, it works fine and my UI is updated with the newly added item. So, this code works...
//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>
Here is the 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();
However, I am having trouble understanding how can I add a new item programmatically and see those changes on the UI.
Essentially, the subscribe() function in the code snippet is listening for external events and needs to insert an item in the list programmatically / update the UI, is not working.
I have been looking for a while and tried various examples from SO and elsewhere, but I cannot get it to work for this rather simple looking case. Any pointers or guidance will be appreciated.
Thanks!
item
andnewitem
refer to insidesubscribe()
? – ExpertSystem May 25 '14 at 21:46