Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

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!

share|improve this question
    
Can you add the code that is listening to the external events? – Anthony Chu May 25 '14 at 21:25
    
@AnthonyChu: I added the subscribe function. Since I have an alert on it with various values, I know the subscribe is working. I think I am messing up how an array value is added to Angular and the two way binding to ensure that it is refreshed on the UI. – DevIntern May 25 '14 at 21:44
    
$scope.$apply(); is unnecessary on your code sample – Dalorzo May 25 '14 at 21:46
    
What does item and newitem refer to inside subscribe() ? – ExpertSystem May 25 '14 at 21:46
    
newitem in subscribe seems to be undefined – Dalorzo May 25 '14 at 21:47

2 Answers 2

up vote 0 down vote accepted

Updated in the question above...but figured I should mention the erring code and the working version here....

//NON WORKING CODE
//***This code (items.push(item) is not working 
//and we do not get the UI updated to show the newly added item.
    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();
share|improve this answer
    
Both version should work (btw $scope.$apply is required in both in order to update the UI - and it is better to wrap it around your code rather than calling it at the end: $scope.$apply(function () { ... });). But of course, if we don't see the whole code it is impossible to spot any problems (e.g. Where did item come from ? What does it look like ? etc). – ExpertSystem May 26 '14 at 10:52
    
@ExpertSystem: Agreed. I probably messed up my code but otherwise both should work. Thanks for your suggestion on wrapping the code in a $scope.$apply(function(){...}) instead of separately calling apply. I incorporated it in the code. – DevIntern May 27 '14 at 5:11
1  
FYI, the main benefit of wrapping the code around $apply() is that you have Angular's exception handling even for code outside of the Angular context. – ExpertSystem May 27 '14 at 6:07
    
Thanks @ExpertSystem. Appreciate you sharing this tip...I did not know that. – DevIntern May 27 '14 at 13:58

No need to pass newItem from HTML to controller since newItem is a $scope variable and controller already has access to it.

Here is the working code:

<!-- html -->
<div ng-controller="MyController">
  <table>
    <tr>
      <td>Status: </td>
      <td><input type="text" ng-model="newItem.status" /></td>
    </tr>
    <tr>
      <td>Priority Summary: </td>
      <td><input type="text" ng-model="newItem.priority_summary" /></td>
    </tr>
    <tr>
      <td colspan="2"><input type="Button" value="Add" ng-click="addItem()" /> </td>
    </tr>
  </table>


  <div ng-repeat="item in items">        
    <p class="priority">{{item.priority_summary}}</p>
    <p class="type">{{item.status}}</p>
  </div>
</div>

<!-- js -->
 .controller('MyController', ['$scope', 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.newItem = {};
        $scope.addItem = function(){
            $scope.items.push($scope.newItem);
            $scope.newItem = {};
        } 

  }]);
share|improve this answer
    
Thanks, but I was having an issue with the subscribe method in my code above. The code sample you have written above was working for me when invoked from the HTML UI. My question was how do I insert new data into Angular from another JS method call. – DevIntern May 27 '14 at 13:56

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.