Angularjs 角度-提交后清除表单输入
我有这样一个简单的表格:Angularjs 角度-提交后清除表单输入,angularjs,Angularjs,我有这样一个简单的表格: <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="s
<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));
$scope.toDoName = "";
}
}
除了现在,因为表单输入是“必需”的,所以表单输入周围有一个红色边框。这是正确的行为,但不是我在这个场景中想要的。。。因此,我想清除输入,然后模糊输入元素。这让我想到:
$scope.addToDo = function() {
if ($scope.toDoName !== "") {
$scope.toDos.push(createToDo($scope.toDoName));
$scope.toDoName = "";
$window.document.getElementById('todo-name').blur();
}
}
现在,我知道在Angular文档中,这样修改控制器中的DOM是不受欢迎的,但是有没有更具角度的方法呢?当您给表单命名时,它会自动添加到
$scope
中
因此,如果您将表单名称更改为“addForm
”('因为我不认为addfrom
是angular的有效名称,不知道为什么),您将有一个对$scope.addForm
的引用
如果使用angular 1.1.1或更高版本,则在
$scope.addForm
上会有一个方法。它应该递归地重新设置表单。或者,如果您不想使用1.1.x版本,您可以对其进行测试和模拟。对于尚未切换到1.1.1的用户,以下是一条指令,当$scope属性更改时,该指令将模糊:
app.directive('blur', function () {
return function (scope, element, attrs) {
scope.$watch(attrs.blur, function () {
element[0].blur();
});
};
});
控制器现在必须在每次提交时更改属性。但至少我们没有在控制器中进行DOM操作,我们不必按ID查找元素:
function MainCtrl($scope) {
$scope.toDos = [];
$scope.submitToggle = true;
$scope.addToDo = function () {
if ($scope.toDoName !== "") {
$scope.toDos.push($scope.toDoName);
$scope.toDoName = "";
$scope.submitToggle = !$scope.submitToggle;
}
};
}
HTML:
我已使其按以下代码工作 HTML部分
<td ng-show="a">
<input type="text" ng-model="e.FirstName" />
</td>
控制器部分
<td ng-show="a">
<input type="text" ng-model="e.FirstName" />
</td>
e、 名字=“”
非常感谢。尽管我仍然需要清除模型,$setPristine()可以很好地处理模糊“添加表单”似乎有效,我可以使用$scope['add-form']而不是点符号访问它。是的,清除模型总是必须的,因为$setPristine不知道您的模型。谢谢你让我知道这个名字!完全错过了,我认为我不应该:)t={};t、 foo-bar=“baz”;ReferenceError:Assignment中的左侧无效如何使用$setPristine?$scope.form name.$model property.$setPristine()用于属性级别或$scope.form name.$setPristine()用于表单级别(影响所有表单控件)谢谢。在1.1.1推出之前,知道这一点很方便。
<td ng-show="a">
<input type="text" ng-model="e.FirstName" />
</td>