javascript AngularJs 空表单并从输入中删除无效状态
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17814564/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJs empty form and remove invalid state from inputs
提问by adamors
I'm using a form to add elements to list that is displayed on the side of the form. Markup is:
我正在使用表单将元素添加到显示在表单侧面的列表中。标记是:
<form name="thingForm">
<input required type="text" ng-model="thing.name"/>
<input required type="text" ng-model="thing.value"/>
<input type="submit" ng-click="addThing(thing)"/>
</form>
<ul>
<li ng-repeat="thing in things">{{thing.name}} with value of {{thing.value}}</li>
</ul>
And in a controller I have:
在控制器中,我有:
$scope.things = [];
$scope.addThing = function(thing) {
$scope.things.push(thing);
$scope.thing = {};
};
Working jsfiddle: http://jsfiddle.net/cXU2H/1/
工作jsfiddle:http: //jsfiddle.net/cXU2H/1/
Now as you can see, I can empty the form by emptying the model, however since the inputs have the required tag the browser still displays an error message (at least Chrome does).
现在如您所见,我可以通过清空模型来清空表单,但是由于输入具有所需的标签,因此浏览器仍会显示错误消息(至少 Chrome 是这样)。
I looked at the similar questions and:
我查看了类似的问题,然后:
- I've also looked at this answer: https://stackoverflow.com/a/16296941/545925however the jsfiddle behaves exactly the same as in my example: after the input is cleared it still has an
ng-invalid-required
class remaining (and it also triggers a HTML5 error message) since I'm not on the 1.1.x branch$setPristine()
is not available for me$setPristine()
behaves the same way
- 我也看过这个答案:https: //stackoverflow.com/a/16296941/545925 但是 jsfiddle 的行为与我的例子完全一样:在输入被清除后它仍然有一个
ng-invalid-required
类剩余(并且它也触发一条 HTML5 错误消息) 因为我不在 1.1.x 分支上,所以我$setPristine()
无法使用$setPristine()
行为相同
I can of course write a function that iterates through the elements of a form and removes every ng-invalid-required
and ng-invalid
class, but that is not the way I would like to solve this. That is what I would do with jQuery.
我当然可以编写一个函数来遍历表单的元素并删除每个ng-invalid-required
和ng-invalid
类,但这不是我想要解决的方法。这就是我会用 jQuery 做的事情。
回答by Ygor Cardoso
Are you using $setPristine right? You can easily see in your fiddle that if you add it, it works. http://jsfiddle.net/X6brs/
你在使用 $setPristine 吗?你可以很容易地在你的小提琴中看到,如果你添加它,它就可以工作。http://jsfiddle.net/X6brs/
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.things = [];
$scope.addThing = function(thing) {
$scope.things.push(thing);
$scope.thing = {};
$scope.thingForm.$setPristine(true);
};
}
回答by adamors
$scope.thingForm.$setPristine();
$scope.thingForm.$setUntouched();
will do the trick.
会做的伎俩。