Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
956 views
in Technique[技术] by (71.8m points)

angularjs - 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();
    }
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...