gpt4 book ai didi

javascript - 手动将 dirty 设置为字段不会修改 css 类 angularJS?

转载 作者:行者123 更新时间:2023-11-30 12:32:13 27 4
gpt4 key购买 nike

我有一个使用 angular js 的表单。在提交表单时,如果字段无效,我会将其设置为脏字段。但问题是即使在将字段设置为脏后,它也不会更改字段上的 CSS 属性。 ng-pristine 类仍然保留在这些元素上。在将字段设置为脏后,它不会将类更改为 ng-dirty

提交表单后您可以看到错误消息,但它没有应用 ng-dirty css 类。

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>

最佳答案

替换

$scope.registrationForm.lname.$dirty

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

$setDirty();

Sets the form to a dirty state.

This method can be called to add the 'ng-dirty' class and set the form to a dirty state (ng-dirty class). This method will also propagate to parent forms.

AngularJS Doc

关于javascript - 手动将 dirty 设置为字段不会修改 css 类 angularJS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27356244/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com