Angular set pristine没有按预期工作

时间:2018-04-25 10:47:41

标签: angularjs angularjs-material

我正在尝试在其中一个输入上创建自定义验证。一切都按预期工作,但仍然应用错误css类。我试过for e in arr$setPristine()首先输入(没有工作),然后在表格上。如果我可以在ng-change中重置样式,那么完美的解决方案就是。



$setUntouched()

self.changeTransferNumber = function () {   
  if (validateRoutingNumber(self.bankTransferNumber)) {
    self.bankInfoForm.bankTransferNumber.$error.validateTransferNumber = false;
    self.bankInfoForm.$setPristine();
    self.bankInfoForm.$setUntouched();
  } else {
    self.bankInfoForm.bankTransferNumber.$error.validateTransferNumber = true;
  }
}
    	




2 个答案:

答案 0 :(得分:0)

您需要在html中传递您的表单名称: -

stats.chisqprob = lambda chisq, df: stats.chi2.sf(chisq, df)

在您的controller / js文件中: -

 <form role="form"  name="Form" id="Form" ng-submit="Form.$valid && saveFormData($event,Form)" novalidate  autocomplete="off">

我对这个问题的理解......

答案 1 :(得分:0)

为什么不使用指令创建自定义验证器?通过这种方式,它很容易重复使用。

&#13;
&#13;
(function() {
	'use strict';
  
  angular.module('myApp', []);
  
  angular.module('myApp').controller('MyController', MyController);
  
  MyController.$inject = [];
  function MyController() {
  	var main = this;
    
    main.routingNumber = '2';
  }
  
  angular.module('myApp').directive('validateRoutingNumber', function() {
  	return {
    	restrict: 'A',
      require: {ngModel: ''},
      bindToController: true,
      controllerAs: '$dir',
      controller: function() {
      	var $dir = this;
        
        $dir.$onInit = function() {
          createValidators();
        };
        
        function createValidators() {
          $dir.ngModel.$validators.routingNumber = function(modelValue, viewValue) {
            var value = modelValue || viewValue;
            //without this if-else it would become a required field
            if (value) {
            	return value.toString().length >= 3 && value.toString().indexOf('1') !== -1; 
            } else {
            	return true; 
            }
            
          }
        }
        
      }
    };
  });
  
}());
&#13;
input.ng-invalid {
  border: 1px red solid;
  background-color: red;
  color: white;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<body ng-app="myApp">
  <div ng-controller="MyController as main">
    <form name="frmMain">
      <input type="text" ng-model="main.routingNumber" name="routingNumber" validate-routing-number>
      <span ng-if="frmMain.routingNumber.$invalid">Needs to have at least three characters and at least one '1'</span>
    </form>
  </div>
</body>
&#13;
&#13;
&#13;