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

时间:2014-12-08 10:46:42

标签: javascript html css angularjs

我有一个使用角度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>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:3)

替换

$scope.registrationForm.lname.$dirty

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

  

$使用setDirty();

     

将表单设置为脏状态。

     

可以调用此方法来添加&#39; ng-dirty&#39;类并设置表单   到一个肮脏的状态(ng-dirty class)。此方法也将传播到   父母表格。

AngularJS Doc