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

Disable style validation in Angular-auto-validate plug-in

Currently, I am working on a project using Angular where we have implemented the [Angular-Auto-Validate] plugin for form validations. While this plugin works seamlessly with various types of form validation and is easy to use, we have encountered a specifi ...

Determining when props are updated in Vue.js 2 when passing an object as a prop

Let's say there is an array feedsArray, with a sample value like this: this.feedsArray = [ { id: 1, type: 'Comment', value: 'How are you today ?' }, { id: 2, type: 'Meet', name: 'Daily ...

Is there a way to extract both a and b from the array?

I just started learning programming and I'm currently working on creating an API call to use in another function. However, I've hit a roadblock. I need to extract values for variables a and b separately from the response of this API call: import ...

What is the best way to display a placeholder instead of the state's value when a page loads?

I'm having trouble displaying the placeholder of an input instead of its state value. When the page loads, it shows an empty select box because the testType state is null initially. How can I make sure that only the placeholder is shown instead of the ...

Discover instances of a string within an array using JQuery

I am currently exploring how to locate occurrences of a specific string within an array on the client side. The examples provided on the JQuery Docs all seem focused on number comparisons, which isn't quite what I need. Essentially, I'm attempti ...

Assign a unique HTML attribute to a child element within a Material-UI component

Currently, I am trying to include the custom HTML5 attribute "data-metrics" in the span element within the ListItemText Material UI component. However, I am facing some difficulty achieving this as per the specifications outlined in the Component API Docum ...

Easily validating forms using javascript

I'm attempting to design a basic HTML form and would like to implement javascript for validating the input values. Below is the form tag: <form action="" onSubmit="return formValidation();" method="Post" name="form"> Here is a section of the ...

The functionality of PHP in relation to the jQuery post feature seems to be malfunction

After developing the JavaScript functionality for this contact form, below is the HTML structure without any CSS styling included: <!-- Contact Form --> <div class="cws-widget"> <div class="widget-title" style="color:#fec20b;">S ...

Is there a way to randomly change the colors of divs for a variable amount of time?

I have a unique idea for creating a dynamic four-square box that changes colors at random every time a button is clicked. The twist is, I want the colors to cycle randomly for up to 5 seconds before 3 out of 4 squares turn black and one square stops on a r ...

Can Acumatica support the loading of external JavaScript files or libraries?

I am currently developing a new Acumatica screen for our company that will involve integrating javascript code to retrieve and display a map object (from ESRI). The challenge is that this code necessitates an external .js file which the javascript code it ...

Why would you need multiple root handlers?

One interesting feature to note is that multiple callback functions can be used as middleware to handle a request. These callbacks can take on different forms - they could be in the form of a single function, an array of functions, or even a combination of ...

Unable to get CSS transition to function properly after adding a class using jQuery

I am trying to create a hover effect that shows an image when the mouse is over a specific div, but for some reason, the transition is not working as expected. I understand that using visibility: hidden cannot be animated. Here is the code snippet: $(d ...

Using the reduce method in JavaScript or TypeScript to manipulate arrays

Just exploring my culture. I have grasped the concept of the reduce principle var sumAll = function(...nums: number[]):void{ var sum = nums.reduce((a, b) => a + b , 0); document.write("sum: " + sum + "<br/>"); } sumAll(1,2,3,4,5); The r ...

Create your very own Youtube player directive in AngularJS with fully customizable external controls

I am looking to integrate a YouTube player into my Angular app and enhance it by adding custom external buttons for playback control. I require a directive that can manage all video functionalities, such as seeking and tracking progress. Although I have ...

I attempted to access the local host using my Android phone, but I was unable to load the complete Angular

Currently, I am utilizing a tomcat server and angularJS to construct a website that relies on an API for retrieving data from the server through HTTP requests. The site functions perfectly when running locally on my machine with tomcat enabled. However, wh ...

I am encountering issues where none of the NPM commands are functioning properly even after updating the

For a few months, I have been using npm without any issues. However, once I installed python/django and created a virtual environment, npm stopped working altogether. An error message similar to the following is displayed: sudo npm install -g react-nativ ...

Provide input to npm when running "my command" and utilize that input within my functions

Consider the contents of app.js const { doCoolStuff } = require("./api/myApi"); // grab parameter from command line and store it in "myParam" doCoolStuff(myParam); ... // more code And Package.json: { "name": "------ ...

When using jQuery and AJAX together, it seems that the POST method is returning

Currently experimenting with Cloud9. The current project involves creating an image gallery. On the initial page: There are a few pictures representing various "categories". Clicking on one of these will take you to the next page showcasing albums fro ...

Converting a string to HTML in Angular 2 with proper formatting

I'm facing a challenge that I have no clue how to tackle. My goal is to create an object similar to this: { text: "hello {param1}", param1: { text:"world", class: "bla" } } The tricky part is that I want to ...

Is there a faster way to create a typescript constructor that uses named parameters?

import { Model } from "../../../lib/db/Model"; export enum EUserRole { admin, teacher, user, } export class UserModel extends Model { name: string; phoneNo: number; role: EUserRole; createdAt: Date; constructor({ name, p ...