有这样的形式
<div ng-controller="FormController as f_ctrl">
<form ng-submit="f_ctrl.submit()" name="myForm">
<input type="text" ng-model="f_ctrl.user.username"
required
ng-minlength="4"/>
<input type="text" ng-model="f_ctrl.user.password"/>
<input type="submit" value="Submit" ng-disabled="myForm.$invalid">
</form>
</div>
和这样的 Controller
.controller('FormController', [function() {
var self = this;
self.submit = function() {
console.log('User submitted form with ' + self.user.username)
}
}]);
我有一个问题:当页面第一次加载时,它立即在用户名字段上显示红色边框,甚至在我开始输入任何内容之前。
我只需要在第一次提交后突出显示无效字段。这可以使用 form.$invalid
来完成吗?
最佳答案
你必须为此使用 $pristine。当表单 Controller 未更改时为真。因此,当您更改文本框数据时,它会出错。
给你的小例子。
<div class="form-group" ng-class="{ 'has-error' : userForm.password.$invalid && !userForm.password.$pristine }">
<input id="passAnime" type="password" name="password" ng-model="user.password" class="form-control input-md" placeholder="Password" tabindex="5" ng-maxlength="25" ng-minlength="6" required>
<span ng-show="userForm.password.$dirty && userForm.password.$invalid">
<p ng-show="userForm.password.$error.required" class="error-messages">
Your password is required.
</p>
<p ng-show="userForm.password.$error.minlength" class="error-messages">
Your password is too short. Minimum 6 chars.
</p>
<p ng-show="userForm.password.$error.maxlength" class="error-messages">
Your password is too long. Maximum 25 chars.
</p>
</span>
</div>
关于javascript - 不要触发 form.$invalid 在第一次加载时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31826792/