I have the following simple form with an type='email' input bound to a model:
<div ng-app>
<h2>Clearing ng-model</h2>
<div ng-controller="EmailCtrl">
<form name="emailForm" ng-submit="addEmail()">
<input type="email" name="email" ng-model="userEmail" placeholder="[email protected]">
<span ng-show="emailForm.email.$invalid && emailForm.email.$dirty">invalid email</span>
<span ng-show="emailForm.$invalid">form invalid!</span>
</form>
<br/>
<button ng-click="clearViaUndefined()">clear via undefined</button>
<button ng-click="clearViaNull()">clear via null</button>
<button ng-click="clearViaEmptyString()">clear via empty string</button>
</div>
</div>
Suppose the user enters an invalid email but then clicks a 'Cancel' button...so the form needs to be reset.
In the ng-click handler for the 'Cancel' button, if I set the value of the model to 'undefined' this does not change the input element's $valid property back to true (nor the form's for that matter).
function EmailCtrl($scope) {
$scope.clearViaUndefined = function () {
$scope.userEmail = undefined;
};
$scope.clearViaNull = function () {
$scope.userEmail = null;
};
$scope.clearViaEmptyString = function () {
$scope.userEmail = "";
};
}
If I set the value of the model to an empty string "" or to null, then the $valid property does get set back to true.
Why is this?
I have a JS Fiddle here demonstrating the behaviour:
http://jsfiddle.net/U3pVM/12830/
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…