Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I add an object to a nested array in AngularJS?
    primarykey
    data
    text
    <p>I'm new to AngularJS. I've researched the theory behind ng-repeats but I cannot find any good examples of 2-way data binding or object creation for nested ng-repeats. I understand that the syntax has changed in recent versions. I'm using 1.1.5. </p> <p>I have post objects that have a nested array of comment objects. I want to be able to add new comment objects to the array of comments in the post. I've tried lots of different versions. </p> <p>This is my HTML:</p> <pre><code>&lt;div id='posts' ng-controller="PostsCtrl"&gt; &lt;ul&gt; &lt;div id='post' ng-repeat="post in posts track by post.id"&gt; &lt;div id='postMedia'&gt; &lt;img ng-click="" ng-src={{post.attachment}} /&gt; &lt;/div&gt; &lt;div ng-click=""&gt; &lt;div ng-click=""&gt;{{post.message}}&lt;/div&gt; &lt;div ng-click=""&gt;{{post.created_at}}&lt;/div&gt; &lt;/div&gt; &lt;h1&gt;Comments&lt;/h1&gt; &lt;div id='comment' ng-repeat="comment in post.comments track by post.comment.id"&gt; &lt;div ng-click=""&gt;{{comment.body}}&lt;/div&gt; &lt;/div&gt; &lt;form ng-submit="addComment()"&gt; &lt;input id="body" type="text" placeholder="Reply…" ng-model="post.comment.body"&gt; &lt;input type="submit" value="Add"&gt; &lt;/form&gt; &lt;/div&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>This is the controller:</p> <pre><code>myApp.controller('PostsCtrl', ['$scope', 'angularFire', function MyCtrl($scope, angularFire) { var url = 'https://inviter-dev.firebaseio.com/posts'; $scope.items = angularFire(url, $scope, 'posts', {}); $scope.commentProp = 'comments'; $scope.addComment = function() { $scope.comments.push($scope.newcomment); } } ]); </code></pre> <hr> <p>SOLUTION:</p> <p>Thanks to Chandermani answer for solving this. I modified the controller slightly because I wanted the to use a key called body in the data store -</p> <pre><code>myApp.controller('PostsCtrl', ['$scope', 'angularFire', function MyCtrl($scope, angularFire) { var url = 'https://inviter-dev.firebaseio.com/posts'; $scope.items = angularFire(url, $scope, 'posts', [] ); $scope.addComment = function(post,comment) { post.comments.push({body:comment}); } } </code></pre> <p>]);</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload