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>
<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>
<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>