Why does Angular not reset form after ng-click event?

Something seems off with my form reset after a ng-click event, am I missing something?

I can successfully submit the form, but it doesn't automatically reset. Here is the error message I receive:

angular.js:12701 POST 500 (Internal Server Error)

The post submission works fine, but the form doesn't clear out as expected.

Check out this jsfiddle link for reference:

https://jsfiddle.net/2fyynf6p/

Here's the main.js code snippet:

var app = angular.module('eli', [], function($interpolateProvider) {
    $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');

});

app.controller('mainCtrl', ['$scope', '$http', function($scope, $http){


    $scope.posts = {};

    $scope.addPost = function(){

        $http.post('/auth/post', {
            title: $scope.post.title,
            body: $scope.post.body

        }).then(function(data, status, headers, config){
            $scope.posts.push(data);
            $scope.postform = "";


        });


    };


}]);

And here's the html code snippet:

<form  name="postform" method="POST" novalidate>
                   {{ csrf_field() }}
                <div class="form-group">
                    <label for="post.title">Title</label>
                    <input ng-model="post.title"  class="form-control" type="text" name="title" placeholder="Enter a title" required/>
                </div>

                <div class="form-group">
                    <label for="post.title">Post</label>
                    <textarea ng-model="post.body" type="text" class="form-control" name="body" id="" cols="10" rows="5"></textarea>
                </div>

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

Answer №1

Here is an example of how you can achieve this:

$scope.addPost = function({
$http.post('/auth/post', {
title: $scope.post.title,
body: $scope.post.body
}).then(function(data, status, headers, config) {
$scope.posts.push(data);
$scope.post.title = "";
$scope.post.body = "";
});
};

Answer №2

Resolved the issue by implementing the following changes. The solution was found within the scope function, but outside of the http post.

var app = angular.module('eli', [], function($interpolateProvider) {
    $interpolateProvider.startSymbol('<%');
    $interpolateProvider.endSymbol('%>');

});

app.controller('mainCtrl', ['$scope', '$http', function($scope, $http){

    $scope.posts = {};

    $scope.addPost = function(){

        $http.post('/auth/post', {
            title: $scope.post.title,
            body: $scope.post.body

        }).then(function(data, status, headers, config){
            $scope.posts.push(data);    

        });

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

    };

}]);

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

width of the cells within the grid table

What is the best way to ensure the width alignment of cells in both the header and main section? I have highlighted the correct option in the image with green checkmarks. Check out the image here. Here is my example and solution: View the code on CodePen. ...

Unusual shadow cast by the box's silhouette

I am currently facing an issue with a box and its shadow. When I close the box, a different shadow lingers behind. I have tried troubleshooting this problem but cannot pinpoint the source. I have included the relevant code files in the specified folders. I ...

An issue occurred when attempting to integrate Angular

Currently, I am in the process of learning AngularJS. To practice, I attempted a simple code snippet in an HTML file: <!DOCTYPE html> <html lang="en" ng-app=""> <head> <meta charset="utf-8"> &l ...

Issues with Javascript functionality on aspdotnetstorefront site

Lately, I've been facing some challenges with my Javascript and jQuery codes when trying to implement them in the storefront. Despite attempting different methods to create a slider, none seem to work within the store environment - even though they fu ...

Utilizing node.js as a standalone web server application

I've developed a node.js-based web server (Javascript file) designed to serve a Javascript-integrated web page for controlling immersive sound on mobile devices. The server utilizes native modules for MIDI and pcap communication, along with express fo ...

React Router Redux causing an infinite loop when navigating back

I recently encountered a strange issue with my React + Redux app. I am using React Router in combination with React Router Redux for routing, and I noticed some unexpected behavior. Clicking the back button once takes me from route 0 to -1 successfully. Ho ...

Revise Script to Duplicate Alt Attribute onto Miniatures

I'm customizing a gallery plugin for a website that I am currently developing, aiming to add support for titles. The script I am using can be found here: DEMO: http://jquery.malsup.com/cycle/pager2.html CODE: All the functionalities are in place e ...

Issues encountered when utilizing a provider alongside a controller for implementing Highcharts visualizations in angularjs

I've been working on an Angular web application that incorporates highcharts (highcharts-ng) integration. My approach was to set up a factory provider where I defined my chart configuration options object: angular.module('socialDashboard') ...

Leveraging JavaScript to generate a downloadable PDF document from the existing webpage

My goal is to have the user click a button labeled 'View PDF' or 'Download PDF' on the current webpage. This button would then execute JavaScript code to generate a PDF based on how the current page appears. I attempted using jspdf for ...

How to extract IDs from a URL in Angular

I'm facing an issue with retrieving the first id from an image URL. Instead of getting the desired id, I am receiving the one after the semicolon ("id" = 1). I have tried various methods but haven't been successful in resolving this issue. Any su ...

What is the best way to transfer Express.js variables to MongoDB operations?

I have been developing a blogging application using Express, EJS, and MongoDB. Feel free to check out the GitHub repository for more details. One of the features I've implemented is a simple pager for the posts within the application. Within the pos ...

I encountered an SyntaxError while working with Ionic. The error message reads: "Unexpected token < in JSON at position 0 at JSON.parse (<anonymous>)."

Here's the code that is causing me trouble: this.http.get('http://localhost/....) .map((res) => res.json()) .subscribe(( this.navCtrl.push(OtpPage,{mobileno:this.mobile}); }, (err) => { console.log(err ...

Issue with the functionality of Bootstrap 5 dismissable alert needs to be addressed

I encountered an issue with the alert in my html code: <div class="alert alert-success alert-dismissible fade show d-flex align-items-center justify-content-center" id="alert" style="display:none;"> <button type=& ...

An error has been thrown stating that the function startTimer is not defined, despite the fact that it is clearly defined

const startBtn = document.querySelector('.startBtn'); const pauseBtn = document.querySelector('.pauseBtn'); const ResetBtn = document.querySelector('.resetBtn'); const time = document.querySelector('.time'); let sec ...

AngularJS: Unable to execute $cookies.remove in current context

Encountering an error message of "$cookies.remove is not a function" while attempting to clear cookies in my Angular application. Double-checked against the Angular documentation and community forum suggestions, but still facing this issue. Below is the s ...

Issue encountered while attempting to pass a function within the data in React

I've encountered an issue while trying to pass a function called sectionOne and then calling it from another component. The error message I received is quite confusing. Error: Warning: Functions are not valid as a React child. This may happen if you r ...

NodeJS: The functionality of my node files relies on the variables defined in another file

For my nodejs app, I have created a script called app.js that serves as the entry point. This script initializes both the expressjs app and the http server. To clarify: The modules mentioned are not npm modules; they are custom files that I have written m ...

jPlayer calculates the "duration" as 1,440 minutes on iOs devices for all mp3 files

My homemade webpage is designed for playing mp3s and viewing pdfs. I'm using jPlayer v 2.9.2 to play the mp3s, which works fine on PC but encounters issues on iPhone. The duration values are incorrect, showing "1439:59" remaining for all files, causin ...

Exploring the functionality of ISO 8601 periods with JavaScript

Has anyone successfully compared ISO 8601 periods in JavaScript to determine which period has a longer duration? For example, is P6M (6 months) longer than PT10M (10 minutes)? I haven't been able to find any built-in solutions for this. Any suggestio ...

Next.js is throwing a TypeError because it does not recognize the function fs.readFileSync

In my JSON data file called total.json, I store information for a chatbot. { "guilds": 3, "users": 21 } Within my index.tsx file, I want to display this data on the webpage, so I attempt the following: import fs from 'fs'; f ...