我有一个使用angular js的表单。在表单提交时,如果字段无效,则将其设置为dirty。但是问题是,即使将字段设置为脏后,它也不会更改字段上的CSS属性。 ng-pristine类仍然保留在这些元素上。在将字段设置为dirty后,它不会将类更改为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();
  
  将表单设置为脏状态。
  
  可以调用此方法以添加'ng-dirty'类并设置表单
  进入脏状态(ng-dirty类)。此方法还将传播到
  家长表格。


AngularJS Doc

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

10-12 15:58