When attempting to use $scope.$setPristine in AngularJS, an error is thrown with the message "TypeError: $scope.$setPrist

I am currently working on developing a simple login form that needs to reset whenever the page is loaded or when the form is submitted.

However, I encountered an error message that reads as follows:

TypeError: Cannot read property '$setPristine' of undefined
at new <anonymous>

Below are the files used (the html file is an Angularjs template):

Javascript

.controller('SigninController', ['$scope', '$firebaseAuth', function($scope, $firebaseAuth){
        $scope.user = {email:"", password:""};
        $scope.loginForm.$setPristine();

        $scope.SignIn = function(){ 

            var ref = new Firebase("https://tipandtrip.firebaseio.com/");
            ref.authWithPassword({
          }, function(error, authData) {
              if (error) {
                console.log("Login Failed!", error);
                $scope.user = {email:"", password:""};
                $scope.loginForm.$setPristine();
            } else {
                console.log("Authenticated successfully with payload:", authData);
                $scope.email = "blass";
                $scope.password = "";
                $scope.loginForm.$setPristine();
            }
        });

        };
    }])
      <div class="container" ng-controller="SigninController">
        <div class="row">
            <div class="col-xs-12">
               <ul class="breadcrumb">
                   <li><a href="index.html">Home</a></li>
                   <li class="active">Login</li>
               </ul>
            </div>
            <div class="col-xs-12">
               <h3>Login</h3>
               <hr>
            </div>
        </div>
        <div class="row row-content">
            <div class="col-xs-12 col-sm-6 col-sm-offset-3">
                <form class="form-horizontal" name="loginForm" ng-submit="SignIn()"  novalidate>
                    <div class="form-group"  ng-class="{ 'has-error has-feedback' : loginForm.email.$invalid && !loginForm.email.$pristine }">
                        <label for="name" class="col-sm-2 control-label">Email</label>
                        <div class="col-sm-10">
                        <input type="email" class="form-control" id="emailid" name="email" placeholder="Email" ng-model="user.email" required>
                        </div>
                        <span ng-show="loginForm.email.$invalid && !loginForm.email.$pristine" class="glyphicon glyphicon-remove form-control-feedback" aria-hidden="true"></span>
                        <span ng-show="(loginForm.email.$invalid || loginForm.email.$error.required) && !loginForm.email.$pristine" class="help-block">Enter a valid email address.</span>

                    </div>
                    <div class="form-group" ng-class="{ 'has-error' : loginForm.password.$error.required && !loginForm.password.$pristine }">
                        <label for="name" class="col-sm-2 control-label">Password</label>
                        <div class="col-sm-10">
                          <input type="password" class="form-control" id="password" name="password" placeholder="Enter Your Passowrd" ng-model="user.password" required>
                        </div>
                        <span ng-show="loginForm.password.$error.required && !loginForm.password.$pristine" class="help-block">Your Password is required.</span>
                    </div>
                    <div class="form-group"  ng-class="{ 'has-error' : invalidChannelSelection }">                       
            <div class="checkbox col-sm-5 col-sm-offset-2">
                            <label class="checkbox-inline">
                                <input type="checkbox"
                                ng-model="user.remember">
                                <strong>Remember me?</strong>
                            </label>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-offset-2 col-sm-10">
                            <button type="submit" class="btn btn-primary" ng-disabled="loginForm.$invalid">Login</button>
                        </div>
                    </div>
                    <div class=" col-sm-12 alert alert-info text-center" id="dbalert_log"></div>
                </form>
            </div>
             <div class="col-xs-12 col-sm-3">

            </div>
       </div>
        <div class="col-xs-12">
            <h3>Reset Password</h3>
            <hr>
        </div> 
       <div class="row row-content">
            <div class="col-xs-12 col-sm-6 col-sm-offset-3">
                <form class="form" role="form" id="resetpass_form">
                    <div class="form-group">
                        <label for="emailReset" class="col-sm-3 control-label">Email</label>                        <div class="col-sm-9">
                        <input type="email" class="form-control" id="email_reset" name="email_reset" placeholder="Email">
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="col-sm-10">
                            <button type="submit" class="btn btn-primary">Reset Password</button>
                        </div>
                    </div>
                   <div class=" col-sm-12 alert alert-info text-center" id="dbalert_reset"></div>
                </form>
            </div>
             <div class="col-xs-12 col-sm-3">

            </div>
       </div>

    </div>

Thank you.

Answer №1

you may encounter an issue because you are triggering $setPristine() before the loginForm is actually instantiated.

Consider this alternative approach:

<form class="form-horizontal" name="loginForm" ng-submit="SignIn()" ng-init="initFunc()"  novalidate>

and modify your JavaScript code as follows:

$scope.initFunc = function(){
   $scope.user = {email:"",password:""};
   $scope.loginForm.$setPristine();
}

feel free to review this jsFiddle for more details.

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

Is there a reason why the child elements do not appear within a div with an ng-if directive when the condition is true?

I'm facing an issue with an ngIf directive in my code. Here's the relevant snippet: <div ngIf="colorSelected" ng-cloak> <h6>My Color</h6> </div> Even when colorSelected is set to true, the inner header element isn&apos ...

Using a pre-defined function as a parameter will not function properly with the event listener

As a beginner, I recently attempted the following: ul.addEventListener("click", function(e) { console.log("Hi"); }); Surprisingly, this code worked just fine. I learned that the function used here is anonymous. However, when I tried ...

Why won't the $emit from custom filter reach the callback in vue-tables-2?

I'm facing a challenge with implementing a custom filter in vue-tables-2 that should emit an event from a nested, single-page component in Vue. It seems like the issue might be related to not handling it correctly in the parent components. Inside the ...

Verify the identity of all REST API requests without the need for a username or password in order to obtain a

I have a unique setup where I am selling products. The API fetches product data from a centralized node back-end and displays it on an angular front-end that is hosted on multiple domains. The challenge I'm facing is the need to authenticate all reque ...

Renew the Look of Dynamic HTML with Updated Styles

In the middle of my website, there is a console that contains links to dynamically update its content using javascript. Everything works smoothly, but the new HTML added dynamically does not have any styling applied to it. Is there a way to refresh the CS ...

What is the best way to style the current element being targeted in React?

In my React application, I am trying to dynamically adjust the height of a textarea element based on its content. I want to achieve this by utilizing an 'onchange' listener to trigger a resize function. While I have successfully implemented the ...

Obtain and send a variety of options for selection button values

I want to create a range selector using submit buttons on my website. In page1.php, I have an array called $array which contains years like 1980, 1990, 2000, 2010, .... The range of this array is updated based on database content. <form method="pos ...

Storing JavaScript-created DOM nodes in MySQL using a combination of jQuery AJAX and PHP

I am working on a basic Javascript client script that includes an HTML button. This script, when clicked, generates new DOM nodes, each with a unique ID based on an incrementing counter. As each node is created, its name (div1, div2, div3, etc) is added to ...

Issue with JSON-to-MUI card mapping causing absence of UI components or error messages

I'm facing a challenge with mapping this JSON data to MUI Cards. Despite no error messages, the content isn't being displayed as expected. Surprisingly, when I make changes unrelated to the issue, the console.log(questionGroups) only shows the JS ...

Issue with Discord.js (14.1) - Message Handling Unresponsive

After developing a sizable Discord Bot in Python, I decided to expand my skills and start learning JS. Despite thoroughly studying the documentation and comparing with my original Python Bot regarding intents, I am facing difficulties getting the message ...

The functionality of jQuery on dropdown list change seems to be malfunctioning in Codeigniter

As a novice in CodeIgniter, I've scoured various StackOverflow threads for a solution to my issue without any luck. Below is the view code causing trouble: <select name="select1" id="select1"> <option value="0">None</option> ...

Changing the hover background color and text color of Material UI Button

I recently developed a custom Appbar component using React.js that includes 3 buttons. I'm looking to enhance the user experience by changing the color scheme when users hover over these buttons. Currently, the background color is set to #3c52b2 and t ...

Is it possible to enlarge a div using "display: table-cell" property when clicked on?

There are various components displayed on my webpage: I require all components to have a minimum height of 150px. If the height is less than 150px, I want to vertically center their text. In case the height exceeds 150px, I aim to truncate the text at 15 ...

Building a listview using Angular, MySQL, and Node.js

As a newcomer to Angular, I've been navigating my way through the learning process with some success but also encountering challenges. Although I've managed to resolve certain issues within the application, such as successfully inserting data int ...

Validating a string using regular expressions in JavaScript

Input needed: A string that specifies the range of ZIP codes the user intends to use. Examples: If the user wants to use all zip codes from 1000 to 1200: They should enter 1000:1200 If they want to use only ZIP codes 1000 and 1200: They should enter ...

JavaScript code to generate a random color for the box shadow effect

Recently, I developed a function that generates random divs containing circles. The function randomly selects a border color for each circle, and this feature is functioning correctly. To enhance the appearance, I decided to add a box shadow to the circl ...

Swap the value of a button's text using a dropdown list when clicked in VueJS with TypeScript

I have a button with a click event that opens a dropdown list. I would like for the button text to be updated and for the selected option to be removed from the dropdown list when the user makes a selection. Currently, using {{interestSortingOptions.label} ...

Deleting outdated files in a temporary uploads directory - NodeJS best practices

My process for removing old files from a tmp upload directory involves the code below: fs.readdir( dirPath, function( err, files ) { if ( err ) return console.log( err ); if (files.length > 0) { files.forEach(function( file ) { ...

Complicated aspects of React and Angular deployment

As I delve into learning React, I find myself a bit puzzled by the various aspects of development and deployment. Are all webpages built using frameworks like React or Angular? Or are they primarily used for single page web applications? Can React be serv ...

Trying to convert <image> from canvas to png or base64 is not functioning properly

Currently, I am dealing with a grid div element that contains various HTML tags such as <div>, <p>, and <img>. I need to convert this grid to canvas and then encode it to base64 for saving on the server using PHP. Can someone assist me i ...