How can I include a nested object in an ng-repeat loop in Angular?

I'm new to using Angular so please excuse my basic question.

Here is the structure of my model for posts and comments:

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

This is how my Angular template looks:

<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>

Below is my Angular component setup:

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;

        });
      }
    ]
  });

I need help figuring out how to add comments to the existing list of comments. Can you point me in the right direction?

Answer №1

Your addComment function needs some adjustments.

Make sure to include the following:

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

and:

ng-model="$ctrl.desc"

In your addComment() function, use the following code:

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

By doing this, you can reset the desc variable for adding new comments.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Learn how to create a smooth and consistent horizontal image slider using JavaScript to manipulate transition transforms

Does anyone know how to create a seamless sliding effect for a series of images in Vuejs? Let's say we have images 1, 2, 3, 4, and 5 When the first slide occurs, the order of images should be: 2, 3, 4, 5, 1 For the second slide: 3, 4, 5, 1, 2 And ...

Utilizing Vuex state within Vue-Router route definitions

My Vuex store setup in main.js looks like this: import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) //initialize the store const store = new Vuex.Store({ state: { globalError: '', user: { ...

Troubleshooting AngularJS: json_encode not producing output under specific circumstances

Currently, I am using $http.get to retrieve data from the server. The controller first calls BackendServices, and within the service, $http.get is invoked: Controller: app.controller('courseController', ['$scope', 'BackendService ...

A guide on implementing a callback function with the iTunes search API

I am having trouble setting up a callback function to effectively utilize the iTunes Store search API. My goal is to achieve the following behavior: const getiTunes = fetch(`https://itunes.apple.com/search?term=${search}&media=movie&limit=200`) ...

Having difficulty incorporating external SASS styles into my React.js project

In most of my projects, I follow a similar process for importing SASS styles. First, I create my react app and then install SASS using the command npm install node-sass. Next, I import my SASS file into my app components as shown below: import React from & ...

What is the process for changing the state of an array in graphql?

Currently, I am facing a challenge with adding an array to a GraphQl schema. Here is what it looks like: type Play { winRatio: [Float] } The intention behind the winRatio attribute is to store the history of all win ratios. For instance, after playing 3 ...

Issue: The 'loopback' module is not found in the NodeJS environment

I can't seem to solve the issue I'm experiencing. Error: Module 'loopback' not found These are the dependencies listed in my package.json file: "loopback": "^3.19.0", "loopback-boot": "^2.6.5", "loopback-component-explorer": "^6.0. ...

Having trouble rendering the response text from the API fetched in Next.js on a webpage

I've written some code to back up a session border controller (SBC) and it seems to be working well based on the output from console.log. The issue I'm facing is that the response comes in as a text/ini file object and I'm unable to display ...

Customizing date colors in JavaScript: A step-by-step guide

var active_dates1 = ["2017-04-02 00:00:00","2014-04-03 00:00:00","2014-04-01 00:00:00"]; $('.datePick', this.$el).datepicker( beforeShowDay: function (date) { for(let date1 of active_dates1){ if (date.getTime( ...

Tips for breaking apart elements of a JavaScript array when a specific delimiter is present in an object property

I am facing a challenge with an array of objects where some properties contain commas. My goal is to split these properties into new objects and recursively copy the rest of the properties into new array elements. For example, consider this original array ...

When working with Vuejs Composition API, I noticed that the value of a Reference object seems to disappear when I

Here is the code snippet that I am working with: <template> {{posts}} </template> <script> import { computed, ref } from 'vue'; import getPosts from '../composables/getPosts.js' import {useRoute} from 'vue-router ...

Getting a specific value from a REST API array in JavaScript: Tips and tricks

After being stuck on this problem for 8 hours, I finally decided to seek help: In my JavaScript file, I am attempting to extract data from a REST API response. The response consists of an array of objects structured like this: [{"start":"2017-04-21 14:40 ...

Using Highmaps in a VueJs application involves passing a state to the mapOptions for customization

I'm currently struggling with passing a vuex state to mapOptions in vuejs components. Here is the code snippet: <template> <div> <highcharts :constructor-type="'mapChart'" :options="mapOptions" class="map">&l ...

React router updates the URL without affecting the actual display

I am facing an issue in my React project where the URL changes when clicking a link, but the view does not update. I have a separate route and links file, and I can't seem to figure out the problem. Here is my index.js: import React from 'react ...

How to customize the checkbox color in Material UI?

I've been attempting to adjust the color of checkboxes and radio buttons. After conducting some research, I stumbled upon this helpful link: Material UI change Input's active color Unfortunately, I keep encountering the following error: (0 , _ ...

The ng-click function within the ng-repeat directive is unresponsive

Whenever I input the parameter as a hard-coded value, the ng-click function works perfectly fine. However, when I try to pass item.Id as the parameter, it does not work even though both instances render the same HTML code. ng-click="viewHistory(100)" ...

What kind of interdependencies exist between modules and controllers?

By specifying that myOtherModule depends on myUtilModule in AngularJS, all values, factories and services defined within myUtilModule can be accessed inside the myOtherModule module as well. Essentially, myOtherModule relies on myUtilModule for functionali ...

The peculiar actions of the Array.function(Object.keys(Obj[0]).map()) function

In my current code implementation, I have a hard coded [0] value that is used in rendering data for a table. However, instead of rendering only the first row as expected, it is displaying all rows. I am confused as to why this is resulting in rendering al ...

The interaction issue in Ionic 4 with Vue js arises when the ion-content within the ion-menu does not respond to clicks

My Vue app has been set up with Ionic 4 using @ionic/vue. Below is the code snippet from the main.js file: import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store&apos ...

Restricting the input field in jQuery to only accept the maximum value based on the

There are two input fields: discountType and discountAmount. My goal is to set restrictions based on the value of discountType: if it's percentage, the discountAmount input should only accept numbers between 0 and 100; if it's absolute, any numbe ...