Angular - 提交后清除表单输入 [英] Angular - clear form input after submit

查看:36
本文介绍了Angular - 提交后清除表单输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的简单表格:

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>

我的控制器如下:

$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 在 Angular 文档中是不受欢迎的——但是有没有更 Angular 的方式来做到这一点?

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?

推荐答案

当您为表单命名时,它会自动添加到 $scope.

When you give a name to your form it automatically gets added to the $scope.

因此,如果您将表单名称更改为addForm"(因为我认为 add-from 不是 angular 的有效名称,不知道为什么),您将获得对 $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.

如果您使用 angular 1.1.1 或更高版本,您将拥有 $scope.addForm 上的 $setPristine() 方法.这应该递归地处理重置您的表单.或者如果你不想使用 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.

这篇关于Angular - 提交后清除表单输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆