【发布时间】:2016-11-09 09:20:43
【问题描述】:
我正在尝试编写一个代码,其中控件仅在输入类型中的文本更改或被清除时才进入代码块。我正在使用以下条件:
if(myfrm.textchecker.$dirty && !myfrm.textchecker.$pristine)
这在我将其更改为 :
之前不起作用 if(!myfrm.textchecker.$dirty && !myfrm.textchecker.$pristine)//completely opposite
这是我的参考代码:
<html>
<head>
<script src="angular.min.js"></script>
</head>
<body ng-app="myApp">
<div ng-controller="outerCtrl">
<form name="myfrm">
<input type="password" name="textchecker" ng-change="processed(ngdata)" ng-model="ngdata" required/>
<input type="submit" name="submit" value="submit">
</form>
<span style="color:red" ng-show="myfrm.textchecker.$error.required">please enter the required text</span>
{{ngdata}}
<p>
{{final}}
</p>
<p>
$dirty : {{ myfrm.textchecker.$dirty }} </br>
$invalid : {{myfrm.textchecker.$invalid }}
</br>
$pristine : {{myfrm.textchecker.$pristine }}
</p>
</div>
</body>
</html>
<script>
var app=angular.module("myApp",[]);
app.controller("outerCtrl",function($scope){
$scope.processed=function(password)
{
if(!myfrm.textchecker.$dirty && !myfrm.textchecker.$pristine)
{
console.log('!myfrm.textchecker.$dirty + !myfrm.textchecker.$pristine');
console.log(!myfrm.textchecker.$dirty + !myfrm.textchecker.$pristine);
// var password=$scope.ngdata;
var strength=0;
//console.log(password);
// alert($scope.ngdata);
// if (password.length > 7) strength += 1
//if password contains both lower and uppercase characters, increase strength value
if (password.match(/([a-z].*[A-Z])|([A-Z].*[a-z])/)) strength += 1
//if it has numbers and characters, increase strength value
if (password.match(/([a-zA-Z])/) && password.match(/([0-9])/)) strength += 2
//if it has one special character, increase strength value
if (password.match(/([!,%,&,@,#,$,^,*,?,_,~])/)) strength += 3
//if it has two special characters, increase strength value
if (password.match(/(.*[!,%,&,@,#,$,^,*,?,_,~].*[!,%,&,@,#,$,^,*,?,_,~])/)) strength +=5
//now we ha
if(strength<=2)
{
$scope.final="Poor";
}
else
if(strength>2 && strength<=5)
{
$scope.final="Weak";
}
else
if(strength>5 && strength<=9)
{
$scope.final="Good";
}
if(strength>9)
{
$scope.final="Strong";
}
}
}
});
</script>
【问题讨论】:
-
只是为了澄清如果您的理解正确 - 即使输入已被触摸(输入任何内容)然后被清除,它仍然被视为
$dirty。所以换句话说,一旦输入,输入就永远不会再次变得原始,除非您明确设置它(仅清除文本值不会使其原始) -
$dirty和$pristine是相反的。您只需要检查其中一项。 -
所以我可以使用 $dirty 或 !$pristine。如果我使用
if($scope.myfrm.textchecker.$dirty && !$scope.myfrm.textchecker.$invalid)会是一个更好的解决方案吗?