Search code examples
javascriptangularjsangularjs-module

in angular how to add nested object to ng-repeat


I'm a complete angular noob so please forgive the rudimentary question.

I have a post/comment structure for my model that looks like this:

[
    {
        "title": "awesome post",
        "desc": "asdf",
        "comment_set": [
            {
                "id": 2,
                "desc": "another awesome comment",
            }
        ]
     }
]

My angular template looks like the following:

<li ng-repeat="post in $ctrl.phones | filter:$ctrl.query | orderBy:$ctrl.created_at" class="media media-clearfix-xs">
<div>{{post.title}}</div>
<ul class="comments">
                                <li ng-repeat="comment in post.comment_set  | orderBy:created_at" clas="media">
                                  <div>{{comment.desc}}
                                </li>
                                <li class="comment-form">
                                  <div class="input-group">
                                    <form ng-submit="$ctrl.addComment()">
                                    <input ng-model="post.comment_set.desc" type="text" class="form-control" />
</form>
                                    <span class="input-group-btn">
                   <input type="submit" class="btn btn-default"><i class="fa fa-photo"></i></input>
                </span>

                                  </div>
                                </li>
                              </ul>

</li>

My angular component looks like this:

angular.
  module('phoneList').
  component('phoneList', {
    templateUrl: '/static/common/angular/phone-list/phone-list.template.html',
    controller: ['$http',
      function PhoneListController($http) {
        var self = this;

        self.addComment = function() {
            self.push({desc:post.comment_set.desc});
          };

        $http.get('api/posts/').then(function(response) {
          self.phones = response.data;

        });
      }
    ]
  });

What am I missing that will add comments to the comments ng-repeat?


Solution

  • Your addComment function is incorrect.

    You should have:

    ng-submit="addComment(post.comment_set)"
    

    and:

    ng-model="$ctrl.desc"
    

    Then, addComment() should be:

    self.addComment(comment_set){
        comment_set.push({desc: self.desc, id: <ID_HERE>});
        self.desc = null;
    }
    

    This way, you reset the desc variable so you can add a new comment