Issue with resetting the form field

Whenever a user opens a modal window to save data, I reset the form fields to blank. This works as expected, but I encountered an issue with AngularJS form validation messages appearing due to dirty check. I tried adding $setPristine() to resolve this, but it resulted in an error stating that $setPristine() is undefined.

main.html

<form id="editMessagesForm" name="editMessagesForm"
    novalidate class="border-box-sizing">
<div class="modalForm"> 
    <div class="modalBorder">
        <div class="row" ng-if="messageNotificationDTO.adminNotificationKey">
            <div class="form-group col-md-12 fieldHeight">
                <label  class="col-md-4">Message Key:</label>
                <div class="col-md-8">
                    <input type="text" class="form-control" id="messageNotificationKey"
                        name="messageNotificationKey"
                        ng-model="messageNotificationDTO.adminNotificationKey"
                        disabled="disabled">
                </div>
            </div>
        </div>
            <div class="row">
                <div class="form-group col-md-12 fieldHeight">
                    <label  class="col-md-4">Message Type:</label>
                <div class="col-md-8">
                        <select name="mesgLookUpcode" class="form-control"
                            ng-model="messageNotificationDTO.adminNotificationTypeCode" required
                            id="mesgLookUpcode"
                            ng-options="adminDataSource.id as adminDataSource.text for adminDataSource in adminDataSource">
                            <option value="">Select...</option>
                        </select>
             </div>
            </div>
        </div>
                <div class="row">
            <div class="form-group col-md-12 fieldHeight">
                <label  class="col-md-4 required">Notification Name:</label>
                <div class="col-md-8">
                    <textarea rows="2" class="form-control"
                        ng-model="messageNotificationDTO.adminNotificationName"
                        name="adminNotificationName"
                        required
                        id="adminNotificationName" txt-area-maxlen="128"
                        ng-disabled="readOnlyFlag"
                        data-tooltip-html-unsafe="<div>{{128 - messageNotificationDTO.adminNotificationName.length}} characters left</div>"
                        tooltip-trigger="{{{true: 'focus', false: 'never'}[messageNotificationDTO.adminNotificationName.length >= 0 || messageNotificationDTO.adminNotificationName.length == null ]}}"
                        tooltip-placement="top" tooltip-class = "bluefill"></textarea>
                        <p class="text-danger" ng-show="editMessagesForm.adminNotificationName.$touched && editMessagesForm.adminNotificationName.$error.required">Message Notification Name is required</p>
                </div>
            </div>
        </div>
    </div>
</div>
    <div class="modal-footer footerMargin">
        <button type="button" class="btn btn-primary pull-right mousedwncall"
            ng-click="saveMessages()" ng-disabled="editMessagesForm.$invalid"
            ng-class="{disableSaveCls:editMessagesForm.$invalid}"
            >Save</button>
        <button class="btn btn-default pull-left mousedwncall"
            ng-click="handleCancelMessageModal()">Cancel</button>
    </div>
</form>

main.js

 $scope.addMessageNotification = function() {
        clearNotificationForm();
        $scope.editMessagesForm.$setPristine();
        $scope.messageNotificationModal.open().center();
    };
    var clearNotificationForm = function () {
      $scope.messageNotificationDTO.adminNotificationTypeCode = [];
      $scope.messageNotificationDTO.adminNotificationName = '';
      $scope.messageNotificationDTO.adminNotificationBody = '';
      $scope.messageNotificationDTO.adminNotificationStartTime = '';
      $scope.messageNotificationDTO.adminNotificationEndTime = '';
      $scope.messageNotificationDTO.activeFlag = '';
    };

ctrl.js

$scope.messageNotificationDTO = {
    adminNotificationTypeCode: [],
    adminNotificationName:'',
    adminNotificationBody: '',
    adminNotificationStartTime: '',
    adminNotificationEndTime: '',
    activeFlag: ''
};
$scope.adminDataSource = adminData.data;

//Set notification grid config and dataSource
$scope.messageGridOptions = messageGridConfig.messagesGridOptions;
messageGridConfig.messagesGridOptions.dataSource = MessageAdminNotificationFactory.getNotificationDataSource();

//Save Notification
$scope.saveMessages = function() {
    MessageAdminNotificationFactory.saveMessageAdmin($scope.messageNotificationDTO).then(function() {
        $scope.messageNotificationModal.close();
        $scope.messageGridOptions.dataSource.read();
        clearNotificationForm();
    });

};
//Add new Notification
$scope.addMessageNotification = function() {
    $scope.messageNotificationModal.open().center();
};
var clearNotificationForm = function () {
  $scope.messageNotificationDTO.adminNotificationTypeCode = [];
  $scope.messageNotificationDTO.adminNotificationName = '';
  $scope.messageNotificationDTO.adminNotificationBody = '';
  $scope.messageNotificationDTO.adminNotificationStartTime = '';
  $scope.messageNotificationDTO.adminNotificationEndTime = '';
  $scope.messageNotificationDTO.activeFlag = '';
  $scope.editMessagesForm.$setPristine();
};

error

 Cannot read property '$setPristine' of undefined

Answer №1

------------------------------------------Update------------------------------------------

Hey there, I have integrated your entire form into the updated plunker. Why do you anticipate $setPristine to activate when you haven't triggered it?

There are two errors you have made. Firstly, you must bind

var clearNotificationForm = function()
to the $scope as shown below. Just using a variable is not sufficient to bind the function to your $scope:

$scope.clearNotificationForm = function()
{
    // All the content above $setPristine should be placed here
}

Secondly, I don't see you invoking the above function anywhere in the form. You need to invoke it using a button, as I have done in the updated plunker. You can find the link to it at the end of the update.

<button class="button" ng-click="reset()">Reset</button>

In your scenario, once you have linked the function to the $scope, your button should look like this:

<button class="button" ng-click="clearNotificationForm ()">Reset</button>

In your case, the function name will be as follows, but you must first bind it to the $scope:

$scope.clearNotificationForm = function()
{
} 

If you found my response helpful, please consider giving it a like. Your support is highly valued.

Here is the updated Plunker


-------------------------------------First Response-----------------------------------

Firstly, ensure that you name your input types with the same ng-model as shown below:

<input name="name1" ng-model="messageNotificationDTO.adminNotificationTypeCode" placeholder="Name" required/>

You need to define your parent object messageNotificationDTO with $scope, and then define the subobjects like adminNotificationTypeCode inside it.

For example:

$scope.messageNotificationDTO = 
{ 
    "adminNotificationTypeCode": "",
    "adminNotificationName": ""
};

Set all the objects to empty and then reset the form like this:

$scope.reset = function()
{  
  $scope.messageNotificationDTO.adminNotificationTypeCode = "";
  $scope.messageNotificationDTO.adminNotificationName  = "";

  $scope.form.$setPristine();
}

Here is a functional example created from your controller code.

plunker

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

Using the inline calendar feature of Bootstrap 3 Datepicker to easily select and capture dates

I've been struggling to extract the selected date from my bootstrap 3 datepicker, and despite attempting to follow the documentation, I still can't grasp it. Here's what I tried: <div id="datetimepicker"> <i ...

Is there a method in CSS animations that allows for endlessly repeating successive animations in a specified sequence?

While working with CSS animations, I encountered a challenge of making two animations occur successively and repeat infinitely without merging keyframes. Is there a way to achieve this using only CSS? If not, how can I accomplish it using JavaScript? I a ...

How to Generate an Array of JSON Objects in JavaScript on a Razor Page using a Custom ViewModel in MVC?

Attempting to populate the array within my script for future charting with D3.JS, I came across some issues. Following advice from this post, I used a specific syntax that unfortunately resulted in an error stating "Uncaught ReferenceError: WebSite is not ...

When using angular $resource.save for savings, the view is forced to redraw and reflow because of the collection watcher

One of the challenges I'm facing involves loading and storing a model using $resource in AngularJS. This particular model is an aggregate with nested collections, which are displayed in an HTML view using ng-repeat. The structure of the model looks l ...

Submitting the Ajax form will result in the quantity of the product in the cart being updated while remaining on

Hello, I am using ajax to keep the user on the same page after submitting a form. If successful, I will use ajax load to load another page that displays the quantity of the product. However, I am facing an issue where each subsequent submit increases the q ...

Assign the ng-repeat item to a variable in the controller's scope

Can anyone help me figure out how to pass a particular item from my view to a function in my controller? Here is the code: The view where I want to pass p.id <tr ng-repeat=" p in projetsListe"> <td>{{p.NomProjet}}</td> <td>{{c ...

The function '$.fn.<new_function>' is not a valid function in jQuery

UPDATE: code link with enhanced formatting: UPDATE: code upgraded with enhancements from JSHint http://pastebin.com/hkDQfZy1 I am attempting to utilize $.fn to establish a new function on jQuery objects by this method: $.fn.animateAuto = function(x,y) { ...

Solutions for accessing data variables outside of a Vue file

Utilizing Vue.js for data binding and filtering has been a rewarding experience. I've set up a Vue object within a .js file and now I aim to pass external data into it. Let's take a look at my test object testFile.js: var vm = new Vue({ el: ...

The mismatch between JSON schema validation for patternProperties and properties causes confusion

Here is the JSON schema I am working with: { "title": "JSON Schema for magazine subscription", "type": "object", "properties": { "lab": { "type": "string" } }, "patternProperties": { "[A-Za-z][A-Za-z_]*[A-Za-z]": { "type" ...

Is it possible for a font to exclude the space character?

I'm currently developing a font detection library that must be extremely compact in size, perfect for direct inclusion on every page of a website. I've managed to shrink it down quite a bit already (compressed to 417 bytes). Take a look at it on ...

Generate a new entry and its linked data simultaneously

The Issue: Picture this scenario: I have two connected models, Library which has multiple Books: var Library = sequelize.define('Library', { title: Sequelize.STRING, description: Sequelize.TEXT, address: Sequelize.STRING }); var Boo ...

Using Node.js to establish communication between HTML and Express for exchanging data

I am faced with a challenge involving two pages, admin.hbs and gallery.hbs. The goal is to display the gallery page upon clicking a button on the admin page. The strategy involves extracting the ID of the div containing the button on the admin page using J ...

Incorporating a JavaScript advertisement zone within a PHP function

Currently in the PHP template, I am trying to embed a JavaScript ad zone inside a function in order to have control over each page's ad placement. Here is what I have: <?php if(is_page('welcome-president')) { oiopub_b ...

What is the best way to condense all JavaScript and CSS files in MEAN.JS for a production setting?

I recently finished creating a basic MEAN.JS application. When using MEAN.JS, I can use the command grunt build to minify the js and css files located in specific folders: css: [ 'public/modules/**/css/*.css' ], js: [ 'public/config ...

Trigger an Ajax request upon user confirmation, which will only be prompted based on the result of a previous Ajax call

Currently, I am facing a challenging issue surrounding asynchronous calls: A specific JQuery function is triggered on user click. This function then requests a PHP file to check if the user input overlaps with existing information in the database. If an o ...

Unable to accurately render selected item from drop-down menu

I am facing an issue with my component that contains a select menu. When I change the value in the select menu, I get the selected value. However, when I click the button to get both values from the two select menus, I see that the value appears as [object ...

What could be causing these warnings to pop up when I am utilizing the useEffect hook in React.js?

Having some trouble with React hooks and JS. I keep getting warnings about missing dependencies in my code, even after reading the documentation. It's all a bit confusing to me. ./src/CustomerList.js Line 32:6: React Hook useEffect has a missing d ...

Mocking in AngularJS: Utilizing the same service with varied functions for unit testing with Jasmine

Exploring a new service, Service A, with various functionalities: The snippet of application code is as follows: angular.module('app').factory('ServiceA', function() { var ServiceA = { _retryItem: null, retryItem: ...

Alternative form for non-javascript browsers in the absence of script

I'm currently working on a landing page for an upcoming product, and I've run into a bit of a snag. <form novalidate method="POST" class="subscribe-form"> <noscript> </form> <form method="POST" action="/ ...

Retrieving information from metaweather API and displaying it on an angularjs webpage

I am in the process of developing a basic weather application that can retrieve weather information for any city. The API I am using has two main stages: 1) Input the name of a city to get its "where on earth ID" (woeid). 2) Use the woeid to search for the ...