Encountering an issue with an undefined property while attempting to submit a form within

I encountered an issue while trying to submit a form inside ng-repeat, resulting in the following error:

TypeError: Cannot read property 'comment' of undefined

If I move the comment form outside of ng-repeat, it works perfectly fine. How can I successfully submit a form inside ng-repeat?

I came across a solution on this topic, but I'm struggling to fully understand it.

ng-form inside ng-repeat with submit button outside of ng-repeat

Note: I am using Laravel 5.5 and AngularJS 1.6v for this project.

Main.js

$scope.myposts = [];
// Form that works outside of ng-repeat adding posts which works flawlessly
$scope.addPost = function(){    
    $http.post('/auth/post', {
        body: $scope.post.body, 
    }).then(function(data, status, headers, config){
        console.log(data);  
        data.data['user'] = {
            name: data.data.name
        },

        $scope.myposts.push(data.data);

    });

    $scope.post.body = '';
};

// Comment form that doesn't work inside ng-repeat

$scope.addComment = function(){

    $http.post('/post/comment',{
        comment_body: $scope.post.comment,
    }).then(function(result){
        console.log(result.data);
        $scope.myposts.push(result.data);


    });

};

HTML

<div id="mypost" class="col-md-10 panel-default" ng-repeat="post in myposts  ">
        <!-- beginnging of ng-repeat post in myposts -->
        <div id="eli-style-heading" class="panel-heading"><a class="link_profile" href="/profile/<% post.user.name | lowercase %>"><% post.user.name %></a></div>
        <div class="panel-body panel" ng-init="getLikeText(post); getLikecount(post)">

            <i style="color:tomato; float:right; font-size:24px;" ng-click="like(post); toggle = !toggle"
            ng-class="{[noheart] : !post.likedByMe, [heart]: post.likedByMe }">
            <h3 style="font-size:20px; margin:20px 0px; text-align:center;"  ng-bind="post.likesCount">   </h3>
            </i>


            <figure>
                <p class="mybody2" ng-model="post.body" editable-text="post.body" e-form="textBtnForm"> <% post.body %></p>
                <p name="post.created_at" ><% post.createdAt %> </p>
            </figure>
            <span>

                <i style="color:red;" class="glyphicon glyphicon-remove" ng-click="deletePost(post)" ng-if="post.deletable"></i>


                <button ng-if="post.update" class="btn btn-default" ng-click="textBtnForm.$show()" ng-hide="textBtnForm.$visible">
                Edit
                </button>

                <span><button ng-if="post.update" type="submit" class="btn btn-primary" ng-click="updatePost(post)">Update</button></span>
            </span>
            <hr>
            <span class="toggle-comments">
                <a ng-show="post.comments.length !== 0"  ng-click="comments = !comments" > View Comments</a>
                <a ng-click="writecomment =! writecomment"> Write A Comment </a>
            </span>
        </div>
        <div ng-show="comments" id="comments" class="col-md-offset-2  panel-default">
            <div style="font-size:10px;" id="eli-style-heading" class="panel-heading">
                <h6><% comment.user.name %><h6>
            </div>
            <figure>
                <p style="padding:10px; min-height:50px; word-wrap:break-word;"> <% comment.comment_body%></p>
            </figure>
        </div>
        <!-- Comment form Inside Ng-repeat -->
        <div class="comment-class animated bounceInUp" ng-show="writecomment">
            <div class="panel-body">
                <ng-form  ng-model="commentForm" name="commentForm" method="POST" novalidate>
                <div class="form-group">
                    <label>Write a Comment</label>
                    <textarea ng-model="post.comment" type="text" class="form-control" name="comment_body" id="" cols="2" rows="2"></textarea>
                </div>
                <button id="eli-style-button" ng-click="addComment()" class="btn btn-primary" type="submit">Submit</button>
                </form>
            </div>
        <!-- END Comment form Inside Ng-repeat -->
        </div>
        <!-- End of ng-repeat post in mypost -->
        </div>

Answer №1

Since there are currently no posts in your $scope, you won't be able to access post.comment. You can update your function to the following:

$scope.addComment = function (post) {

    $http.post('/post/comment', {
        comment_body: post.comment,
    }).then(function (result) {
        console.log(result.data);
        $scope.myposts.push(result.data);
    });
};

Make sure to update the HTML as well:

<button id="eli-style-button" ng-click="addComment(post)" class="btn btn-primary" type="submit">Submit</button>

If you need to submit a comment or pass an index, you can use myposts[index].comment instead.

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

Utilizing window.location.reload just once within $ionicPlatform.ready [Ionic]

In the app.js file, I am initiating an OAuth Process within the device ready function using InAppBrowser. The process involves obtaining a token which is then checked to redirect to a specific view. .run(function($ionicPlatform,$rootScope,$http,jwtHelper, ...

Django is failing to include CSRF token in response to a AJAX GET request made from angularJS

Working on an application that utilizes AngularJS on the frontend and Django as a REST service on the backend, I encountered an issue while trying to send JSON data using a POST request - specifically, the csrf-token problem (CSRF token missing or incorrec ...

Obtain the prototype function

I'm facing an issue with my code: function Param(){ this.name = 'sasha' this.method = function(){ return this.name + 'native method' } this.pro= function(){ debugger // Param.prototype.method() //undefined proto met ...

Ways to determine if a user is able to receive direct messages

I am facing an issue with a DM command. It seems to work properly, but when I try to DM a user who has disabled their DMs, user.send('test') triggers an error: UnhandledPromiseRejectionWarning: DiscordAPIError: Cannot send messages to this user ...

Sending multiple objects from ASP.NET C# code to a JavaScript file

My code works on the HTML page: document.getElementById('<%=IdOstan.ClientID %>').options.length = 0; This code is part of a function where the object is found and the code runs successfully. However, when I move the code to a separate JS ...

Using an Array as a prop in a React component: A step-by-step guide

Currently, I am in the process of learning React by building a website to gain more familiarity with it. As part of my project, I have been experimenting with the "use-dencrypt-effect" npm package. However, I encountered an issue where setting its values v ...

What is the best way to create a backup copy of my project using git?

To ensure the safety of my project, I took the necessary steps to back it up. First, I initialized a repository using git init Following that, I committed all files by executing git add . git commit -am "first commit" Now, the next step involves pushin ...

The React.js component search test encounters errors in locating components

I have been working on a React app that utilizes Redux and React-router. I am currently writing tests using React TestUtils, and I encountered an issue with the following test results: The first expect statement is successful: expect(nav).to.have.length(1) ...

Is there a way to stop a jquery event before it begins and target a specific one instead?

I'm facing a challenge with the initial load of my webpage where the header appears in 3 parts slowly and dramatically. On top of that, I have tabs that trigger transitions between different content "pages." The issue arises when a tab is clicked befo ...

What is the best way to eliminate elements from an array depending on whether their index is odd or even?

I am attempting to organize an array based on its odd and even indexes, then pass this data as a prop to another component. Here is my approach: The array I am working with is called products (data from WooCommerce). const products = [ { attributes: ...

Tips for refreshing an element after modifying a data-* attribute

I have an element that has the following CSS style: #element:after { content: attr(data-percent); } In an attempt to change the data-percent attribute using jQuery, I used this code: $('#element').data('percent', '50%'); ...

Python's Selenium RC is limited to sending text to only one tinymce control on a page

Currently, I am working on writing automated test scripts with Python (2.7) and Selenium RC (2.42.1) for a webpage that has multiple tinymce controls (2 to be exact). The code I have been using so far is as follows: sel.focus( field_values[ id_value ] + " ...

The webservice will return a boolean value by utilizing Ajax technology

Recently, I encountered a jQuery prompt for password validation that utilizes an Ajax webservice. However, I'm uncertain about how to handle the Ajax call and ensure the function is boolean. I just started working with Ajax and webservices approximat ...

Implementing defaultProps in conjunction with withStyles

Currently, I am in the process of developing a component using material-ui withStylers and defaultProps. However, I have encountered an issue where the props of the component are not being retrieved in the styles objects unless they are explicitly passed t ...

send a variable to a function in a random sequence

In my code, I have a function defined as follows: let showNotification = function(a,b,c,d,e,f){ console.log(a,b,c,d,e,f); } When calling this function, it is crucial to pass parameters in the correct order. For example, if I want to omit values for c, ...

Loading slides in bxSlider using ajax

Is there a method to dynamically insert a slide into bxSlider via ajax without affecting its smooth transition? I am looking to initially display the contents of only one slide upon page load, and then have subsequent slides loaded when the next or previo ...

No content appears on the multi-form component in React

After several attempts at building a multi-step form in React, I initially created a convoluted version using React.Component with numerous condition tests to determine which form to display. Unsatisfied with this approach, I decided to refactor the code f ...

How do you send a token with $resource in AngularJS?

I am attempting to convey a token via headers in my $resource requests. Typically, you can use the following code: $http.defaults.headers.common in the .config file. However, I do not have access to these when the application first initializes, so I de ...

Utilizing a Jasmine server in standalone mode for testing AngularJS factories

I have been diving into the world of AngularJS testing by using a stand-alone jasmine server. While I was able to successfully test a controller, I ran into some issues when trying to test a factory that I had created. The error message I encountered was: ...

What is the best way to change the sorting of an array in state when it is clicked on

Developed several functions to sort movies by rating, stock, and title upon clicking. One thing I'm attempting to achieve is the ability to toggle between sorting movie titles in ASC order on one click and DESC on the second click. To accomplish this, ...