Does manually changing the "dirty" setting of a field affect the CSS classes in AngularJS?

I am facing an issue with my AngularJS form. Even after setting the fields to dirty on form submission, the CSS property does not change as expected. The ng-pristine class remains on the elements instead of changing to ng-dirty.

Although error messages are displayed after submitting the form, the ng-dirty css class is not being applied.

var sampleApp = angular.module("sampleApp", []);

sampleApp.controller('sampleCtrl', ['$scope', '$http', '$timeout',
  function($scope, $http, $timeout) {
    $scope.userData = {

      fname: "",
      lname: ""
    };


    $scope.submitted = false;
    $scope.submitForm = function(registrationForm) {
      $scope.registrationForm.fname.$dirty = true;
  $scope.registrationForm.lname.$dirty = true;
      if (registrationForm.$invalid) {
        alert("form validation error.");
        return;
      } else {
        alert("form submitted successfully.");
      }

    }
  }
]);
input.ng-invalid {
  border: 1px solid red;
}
input.ng-valid {
  border: 1px solid green;
}
input.ng-pristine {
  border-color: #FFFF00;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.4/angular.min.js"></script>
<script src="script.js"></script>
<html ng-app="sampleApp">

<body ng-controller="sampleCtrl">
  <form name="registrationForm" ng-submit="submitForm(registrationForm)" novalidate>
    First Name*
    <br>
    <input type="text" name="fname" ng-model="userData.fname" required>&nbsp;&nbsp;
    <span ng-show="registrationForm.fname.$dirty && registrationForm.fname.$error.required">
First name is required.
</span>

    <br>Last Name*
    <br>
    <input type="text" name="lname" ng-model="userData.lname" required>&nbsp;&nbsp;
    <span ng-show="registrationForm.lname.$dirty && registrationForm.lname.$error.required">
Last name is required.
</span>
    <br>
    <br>
    <input type="submit" value="Submit">
  </form>
</body>

</html>

Answer №1

Update your code by changing

$scope.registrationForm.lname.$dirty

to the following

$scope.registrationForm.lname.$setDirty();

$setDirty();

This function sets the form to a dirty state.

By calling this method, you can add the 'ng-dirty' class and mark the form as dirty (ng-dirty class). This change will also affect parent forms.

Take a look at AngularJS Documentation 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

Issue with the alphabetical ordering of subpages

My PageSidebar.js component lists child pages alphabetically. https://i.sstatic.net/DZro1.png However, when I navigate to a child page, the alphabetical order is not maintained. https://i.sstatic.net/fRVgO.png I've tried multiple solutions but hav ...

Ensuring compatibility of peerDependencies through devDependencies in npm3

With the recent update to NPM 3, automatic resolving of peer dependencies has been removed. This poses a challenge when developing a plugin/library for consumption by another application. If the underlying library uses peerDependencies, it requires manual ...

The error message "Unable to map props.theTodos" is displayed

I'm facing an error message while compiling: "TypeError: props.theTodos.map is not a function". I've been struggling with this issue for quite some time, but I haven't found a solution yet as I'm using hooks instead of class components. ...

Is there an effective method for identifying the user's browser and preventing them from accessing the page?

Hey there! I'm looking to restrict user access to my page only if they are using Chrome or IE8-9. I've implemented this restriction in the code behind, as shown below, and attempted to hide the main div element. protected void Page_Load(object ...

The Content Security Policy is blocking other sources because it is set to 'self

Having these two inline script tags: <script async defer src="https://apis.google.com/js/api.js"></script> <script async defer src="https://accounts.google.com/gsi/client"></script> important to note: attempted ...

Creating a Cancel Button in JSP/HTML/JS/CSS Form: A Step-by-Step Guide

It is necessary to incorporate the functionality of "save" and "cancel" in the JSP code for this particular form. By selecting "save", the data entered into the form will be submitted to its intended destination. Alternatively, choosing "cancel" will dismi ...

Using an AJAX post request to update the value of a CKEditor post with the

I am currently attempting to use AJAX to post the value of a CKEditor textarea. I have come across code in this community that looks like this: for (instance in CKEDITOR.instances) { CKEDITOR.instances[instance].updateElement(); } The issue I am encounte ...

I need assistance with incorporating a datepicker feature using jQuery UI

Can someone please assist me? I am trying to incorporate a datepicker (Jquery UI) and add an additional function in the script for counting, but my understanding of jquery is limited. (My English skills are also lacking, apologies in advance) I would dee ...

Step-by-step guide to importing a directory in ReactJS

Is there a way to create an input that can upload an entire directory with all its folders intact? I attempted the following code: <input ref={wrapperRef} id="file-upload" name="file-upload" type="file" ...

The media query is functioning correctly with max-device-width but is not responding as expected with max-width

I've been trying to optimize my website for tablet use, and I've run into an issue with my external CSS file. When I include it like this: <link rel="stylesheet" media="screen and (max-device-width: 960px) and (max-device-height: 1280px)" hre ...

Exploring the Access Method for a Different Addon

Seeking to streamline my Dashboard using Google Analytics Data. I've been utilizing this Addon https://developers.google.com/analytics/solutions/google-analytics-spreadsheet-add-on to retrieve the necessary data. Is there a way to interact with the me ...

Sorting data using the each() method in JavaScript

I am working on updating dynamic data in an HTML template using AJAX to fetch new currency rates from a database without having to refresh the entire page. Here's an example of a Laravel blade template: @foreach ($currencies as $currency) <div ...

What is the best way to organize parent-child data retrieved from a database using JavaScript?

My goal is to showcase information about parent (Survey) and child (Survey participants) details retrieved from the Salesforce database. I am utilizing LWC (Lightning Web Component) for this purpose. An issue arises in LWC where direct access to related o ...

The find function within $(this) is malfunctioning

I'm having issues with displaying/hiding content when clicking on a table row. Here is the simplified code snippet: HTML: <table> <tr onclick="showDetails()"> <td>Some text <br> <span class="hiddenC ...

Showing a collection of objects in a React component

**Recently started learning React and Node, and decided to fetch data into a functional component by following various tutorials. I successfully set up the server, connected it to the database, and fetched the data in React as per the tutorial instruction ...

An error has occurred while trying to declare Symbol InputText during an Angular production build

Currently, I am facing an issue while trying to export the primeng modules from a file. During the test build, I do not encounter any errors. However, when I proceed with the production build, I come across the following error: ERROR in Symbol InputText de ...

Adjust the vertical alignment of the Bootstrap Navbar Container

Seeking a solution to modify the default positioning of a container within the Bootstrap navbar. By default, it is vertically centered in the navbar wrapper (refer to the image below), but I would like it to be aligned to the top. https://i.sstatic.net/XU ...

Getting rid of all CSS properties currently set for the Mobile view

Utilizing third-party library components in my project. The library includes components that come with predefined styles for mobile devices. I am seeking to completely UPDATE these properties within my own code. When I say "update," I mean removing all th ...

Send the array of data to the table in a separate component

I am currently working on developing a basic online shop using React. For testing purposes, I have not integrated it with any API or database yet. Instead, I am utilizing an array of data to display items on the homepage. My goal is to enable visitors to a ...

What is the process for automatically saving associated models when saving the main model?

In my quiz manager, I am working on allowing users to add questions and edit the answers for those questions. My goal is to have a single save button that saves both the questions and their corresponding answers. However, when trying to access and call the ...