角 - 清除表单输入后提交 [英] Angular - clear form input after submit
问题描述
我有一个简单的形式,像这样:
I have a simple form like so:
<form name="add-form" data-ng-submit="addToDo()">
<label for="todo-name">Add a new item:</label>
<input type="text" data-ng-model="toDoName" id="todo-name" name="todo-name" required>
<button type="submit">Add</button>
</form>
我的控制器如下:
with my controller as follows:
$scope.addToDo = function() {
if ($scope.toDoName !== "") {
$scope.toDos.push(createToDo($scope.toDoName));
}
}
我想要做的是明确的文字输入提交后,所以我只需清除模型值:
what I'd like to do is clear the text input after submission so I simply clear the model value:
$scope.addToDo = function() {
if ($scope.toDoName !== "") {
$scope.toDos.push(createToDo($scope.toDoName));
$scope.toDoName = "";
}
}
除了现在,因为'需'的形式输入我避开表单输入一个红色边框。这是正确的行为,但不是我想在这种情况下...所以不是我想清除输入,然后模糊输入元素。这使我:
Except now, because the form input is 'required' I get a red border around the form input. This is the correct behaviour, but not what I want in this scenario... so instead I'd like to clear the input and then blur the input element. Which leads me to:
$scope.addToDo = function() {
if ($scope.toDoName !== "") {
$scope.toDos.push(createToDo($scope.toDoName));
$scope.toDoName = "";
$window.document.getElementById('todo-name').blur();
}
}
现在,我知道修改从这样的控制器中的DOM是建立在角文档中皱起了眉头 - 但有没有这样做的多棱角的方式。
Now, I know that modifying the DOM from the controller like this is frowned upon in the Angular documentation - but is there a more Angular way of doing this?
推荐答案
当你给一个名称,你的形式,它会自动被添加到 $范围
。
When you give a name to your form it automatically gets added to the $scope
.
所以,如果你改变你的窗体名称为 addForm
(因为我不认为添加 - 从
是棱角分明,不知道为什么),你就会有一个参考 $ scope.addForm
一个有效的名称。
So if you change your form name to "addForm
" ('cause I don't think add-from
is a valid name for angular, not sure why), you'll have a reference to $scope.addForm
.
如果您使用的角度1.1.1或以上,你就会有一个<一个href=\"https://github.com/angular/angular.js/commit/733a97adf87bf8f7ec6be22b37c4676cf7b5fc2b\"><$c$c>$setPristine()$c$c>方法上的 $ scope.addForm
。应采取递归重置形式的照顾。或者如果你不想使用1.1.x的版本中,您可以看看源并效仿。
If you use angular 1.1.1 or above, you'll have a $setPristine()
method on the $scope.addForm
. which should recursively take care of resetting your form. or if you don't want to use the 1.1.x versions, you can look at the source and emulate it.
这篇关于角 - 清除表单输入后提交的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!