1

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!

9
  • Can you add the code that is listening to the external events? Commented May 25, 2014 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. Commented May 25, 2014 at 21:44
  • $scope.$apply(); is unnecessary on your code sample Commented May 25, 2014 at 21:46
  • What does item and newitem refer to inside subscribe() ? Commented May 25, 2014 at 21:46
  • newitem in subscribe seems to be undefined Commented May 25, 2014 at 21:47

2 Answers 2

0

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();
Sign up to request clarification or add additional context in comments.

4 Comments

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: 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.
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.
Thanks @ExpertSystem. Appreciate you sharing this tip...I did not know that.
0

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 = {};
        } 

  }]);

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.