Reset form upon submission

When submitting a form and adding the contents to an array, I encounter an issue where the item added to the array remains linked to the form. How can I add the item to the array and then clear the form, similar to using jQuery's reset() function?

Below is my template:

<div class="col-xs-12" ng-controller="ResourceController">
    <div class="col-md-4">
        <h3>Name</h3>
    </div>
    <div class="col-md-8">
        <h3>Description</h3>
    </div>
    <form class="form-inline" role="form" ng-repeat="item in resources">
        <div class="form-group col-md-4">
            <input type="text" class="form-control" value="{{ item.name }}"/>
        </div>
        <div class="form-group col-md-7">
            <input type="text" class="form-control" value="{{ item.description }}"/>
        </div>
    </form>
    <form class="form-inline" role="form" name="addResourceForm" ng-submit="addResource()">
        <div class="form-group col-md-4">
            <input type="text" class="form-control" name="name" ng-model="name" placeholder="Name"/>
        </div>
        <div class="form-group col-md-7">
            <input type="text" class="form-control" name="description" ng-model="description" placeholder="Description"/>
        </div>
        <div class="form-group col-md-1">
            <button type="submit" class="btn btn-default">Add</button>
        </div>
    </form>
</div>

Here is the corresponding controller:

(function(){
    var app = angular.module('event-resources', []);
    app.controller('ResourceController', function($scope){
        $scope.addResource = function(){
            $scope.resources.push(this);
        }

        var defaultForm = {
            name : '',
            description: ''
        };

        $scope.resources = [
         {
            name: 'Beer',
            description: 'Kokanee'
         },
         {
            name: 'Pucks',
            description: 'Black Round Things'
         }
       ]
    });
})();

Answer №1

Utilize the angular.copy() function to duplicate the item data into the resources array, allowing you to safely empty the item data. This method creates a thorough copy of the object, ensuring accuracy.


Alternatively, consider a more straightforward approach that eliminates the need for additional method calls:

$scope.addResource = function() {
  $scope.resources.push({
    name: $scope.name,      // manually recreate object (efficient for simple objects)
    description: $scope.description
  });
  $scope.name = "";         // reset the values.
  $scope.description = "";
};

Answer №2

function addNewResource() {
    resourcesList.push(angular.copy(this));
    nameInput = "";
    descriptionInput = "";
}

Add a new resource to the list by making a copy and then resetting the name and description fields.

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

Ensure that the execution of the function is completed before moving on to the next iteration within a $.each loop

While I'm not an expert in JS or jQuery, I'm currently working on coding a chat application that requires the following functionality: Retrieve conversation list through an AJAX call Display the conversations on the left side of the webpage aft ...

Error: Invalid Argument - The argument 'PanelController' is expected to be a function, but it is undefined

Here is a snippet of my HTML code: <body ng-controller="StoreController as store"> ........... <section ng-controller="PanelController as panel"> <ul class="nav nav-pills""> <li ng-class="{active:panel.isSe ...

Retrieve the data from a Sequelize Promise without triggering its execution

Forgive me for asking, but I have a curious question. Imagine I have something as simple as this: let query = User.findAll({where: {name: 'something'}}) Is there a way to access the content of query? And when I say "content," I mean the part g ...

The h3 tag listener is not functioning as expected

I'm seeking assistance with the listeners for my pomodoro clock, specifically for minBreak and plusBreak. Oddly enough, the listeners for minWork and plusWork in jQuery are functioning properly, but the ones for minBreak and plusBreak are not. Any ins ...

Issues surrounding the determination of CSS attribute value using .css() function within a variable

I have been working on a function to change the color of a span dynamically from black to a randomly selected color from a predefined list. However, I am encountering an issue with the .css("color", variableName) part of my code and suspect that my synta ...

What is the best way to adjust the height and width of a div when it comes into view through scrolling?

How can I automatically and frequently change the size of my div when it is scrolled into view? HTML <div id="contact" class="fadeInBlock"> <div class="map"> <div class="pointer"> <div class="dot"></div& ...

Getting specific information from a cell in a table within an AngularJS application

I need to extract the data "Crab" from this table: Sushi Roll FishType Taste Level Cali Roll Crab 2 Philly Tuna 4 Rainbow Variety 6 Tiger Eel 7 Here is the code snippet that currently re ...

"Firebase offers the flexibility to have several 'apps' configured, both on the client side and the server

Currently, I have a firebase app set up in my project for SSR using firebase-admin. However, I now want to add firebase@8 to be able to utilize it on the client-side and eventually apply firestore rules. The issue arises when I try to use firebase@8, I enc ...

Updating an SVG after dynamically adding a group with javascript: a step-by-step guide

Currently, I am working on a circuit builder project using SVG for the components. In my HTML structure, I have an empty SVG tag that is scaled to full width and height. When I drag components from the toolbar into the canvas (screen), my JavaScript functi ...

What could be the reason for the absence of this Javascript function in my attribute?

I have been working on an app using electron, and I have a function that successfully adds tabs to the app. The issue arises when I try to add tabs via JavaScript with the onclick attribute - they show up as expected but do not execute the code to hide and ...

Issue with Three.js: The mouse hover effect does not revert back to the previous color

Currently, I am working on creating a pattern using Three.js. The goal is to change the color of a face to gray when the user hovers over it with the mouse, and then revert it back to its original light blue color when the mouse moves away. Unfortunately, ...

Having trouble displaying API values in b-form-select component in Vue.js?

I am using an API to fetch users data and I want to bind these users to a b-form-select component in Bootstrap Vue. However, after making the request, I only see "null" in the b-form-select. Here is my request: getAllUsers() { axios.get(&a ...

Different Ways to Customize Button Click Events in Angular 9 Based on Specific Situations

In my Angular 9 web application development, I frequently need to integrate Bootstrap Modals like the example below: <div class="modal" tabindex="-1" role="dialog"> <div class="modal-dialog" role="do ...

Injecting dependencies in AngularJS when utilizing the controller-as syntax: A how-to guide

As I dive into the controller-as feature outlined in the documentation, I'm refining one of my controllers to align with their recommended syntax. However, I'm facing a challenge when it comes to injecting the $http service into my search() funct ...

A beginner's guide to handling multiple events with @click in Vue.js

In my project, I am developing a task manager application utilizing Vue.js, Vuetify, and Firebase. When the user clicks on "Add new note," a Vuetify dialog box pops up, prompting them to input data. Once they click save, the dialog box closes, and the inpu ...

Guide to creating a Map with typescript

I've noticed that many people are converting data to arrays using methods that don't seem possible for me. I'm working with React and TypeScript and I have a simple map that I want to render as a list of buttons. Here is my current progres ...

The choice between using inline style objects with React or utilizing traditional CSS classes presents distinct advantages and

Is there a discernible difference between utilizing an inline style object for react components and using a normal CSS class through the className attribute? Even when wanting to modify styles based on a specific event, simply changing the className should ...

Developing a web application using Yeoman generator to scaffold an AngularJS frontend with an Express server

I am currently experimenting with using ExpressJS alongside the pre-built version of Angular provided by the Yeoman generator for AngularJS. I have opted to utilize the scaffolding created by the Yeoman Team rather than relying on frameworks like angular-f ...

JavaScript Sort function malfunctioning and not correctly sorting

I am having trouble sorting div elements by price values. The code seems to be working fine, but the sorting of numbers doesn't appear to be completely accurate. For example, in my jsfiddle, when the button is clicked, the number 21.35 is displayed a ...

Issue with receiving output from tessearct.js in PDF format

I am currently working on a basic javaScript OCR (Optical Character Recognition) application using tesseract.js. I have included {tess_create_pdf: "1"} in the .recognize() method to receive the result in PDF format, but it seems to be malfunctioning. Can ...