gpt4 book ai didi

javascript - AngularJs 空表单并从输入中删除无效状态

转载 作者:数据小太阳 更新时间:2023-10-29 04:10:43 27 4
gpt4 key购买 nike

我正在使用表单向显示在表单一侧的列表添加元素。标记是:

  <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>

在 Controller 中我有:

$scope.things = [];
$scope.addThing = function(thing) {
$scope.things.push(thing);
$scope.thing = {};
};

工作 jsfiddle:http://jsfiddle.net/cXU2H/1/

现在如您所见,我可以通过清空模型来清空表单,但是由于输入具有必需的标签,浏览器仍然显示错误消息(至少 Chrome 会显示)。

我查看了类似的问题并且:

  • 我也看过这个答案:https://stackoverflow.com/a/16296941/545925但是 jsfiddle 的行为与我的示例中的行为完全相同:清除输入后,它仍然有一个 ng-invalid-required 类剩余(并且它还会触发 HTML5 错误消息)
  • 因为我不在 1.1.x 分支上 $setPristine() 对我不可用 $setPristine() 表现同样

我当然可以编写一个函数来遍历表单的元素并删除每个 ng-invalid-requiredng-invalid 类,但那不是我想解决这个问题的方式。这就是我要用 jQuery 做的事情。

最佳答案

你用的 $setPristine 对吗?你可以很容易地在你的 fiddle 中看到,如果你添加它,它就会起作用。 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);
};
}

关于javascript - AngularJs 空表单并从输入中删除无效状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17814564/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com