在继承同行开发人员的项目之后,我仍然是第一天使用AngularJS。我想知道,我的界面上有一个登录/注册表单,一旦提交了项目/表单就会隐藏。现在,一旦用户提交了有正确或正确的方法来清除它的条目形式并恢复项目上的.ng-pristine类。这样做的原因是,如果用户选择注销然后再次登录(或其他用户希望注册),则表格已填充并且已经应用了验证css。我不想要这个,我希望一切都是空的,不应用CSS。
我可以用JavaScript(很明显)这样做,但是AngularJS是一种不同的方法我想知道我是否应该以另一种方式处理这个问题,而不是遍历表单项并在清除它的值时为每个项添加一个类。 / p>
这是我的一个表格的例子
<form name="signupForm" novalidate ng-submit="register(user)">
<div><label for="email">email:</label><input type="email" id="email" name="email" required ng-model="user.email" ng-minlength=4></div>
<div><label for="userName">Username:</label><input type="text" name="userName" id="userName" ng-model="user.userName" required ng-pattern="/^[A-Za-z0-9 \-_.]*$/" ng-minlength=4></div>
<div><label for="firstName">Vorname:</label><input type="text" name="firstName" id="firstName" ng-model="user.firstName" required ng-pattern="/^[A-Za-z \-_.]*$/" ng-minlength=3></div>
<div><label for="lastName">Nachname:</label><input type="text" name="lastName" id="lastName" ng-model="user.lastName" required ng-pattern="/^[A-Za-z \-_.]*$/" ng-minlength=4></div>
<div><label for="password1">Passwort:</label><input type="password" name="password1" id="password1" ng-model="user.password1" required ng-minlength=4></div>
<div><label for="password2">Passwort wiederholen:</label><input type="password" name="password2" id="password2" ng-model="user.password2" valid-password2 ng-minlength=4 pw-check="password1"></div>
... and so on
非常感谢
答案 0 :(得分:2)
表单将显示在其名称下的正确范围内,即$scope.signupForm
。此外,填充表单的对象是$scope.user
。在您的控制器中,执行:
$scope.user = {}; // or new User() if it is your case
$scope.signupForm.$setPristine();
如果$scope.signupForm
是undefined
,请将控制器直接放在表单上,并将上面的代码(以及其他任何适用的内容)放在这个新控制器中:
<form name="signupForm" novalidate ng-submit="register(user)"
ng-controller="NewCtrl">
(这可能是由于原始控制器下的示波器嵌套造成的。)
答案 1 :(得分:1)
请参阅这篇文章:
Reset form to pristine state (AngularJS 1.0.x)
在主要问题中,您参考了AngularJS上的问题和拉取请求。在简历中,您必须对表单使用$ setPristine()方法。
希望它有所帮助!
答案 2 :(得分:0)
var app = angular.module('App', []);
app.controller('formController', function($scope, $document){
$scope.Clear = function(){
angular.forEach(angular.element($document[0].querySelectorAll('input[type=text], input[type=email], input[type=password]')), function (elem, index) {
elem.value = '';
/*
Just extra do something
elem.parent().parent().removeClass('has-error has-success');
elem.parent().parent().children().find('span').removeClass('glyphicon-exclamation-sign glyphicon-ok');
*/
});
$scope.myForm.$setPristine();
}
});
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.5/angular.min.js"></script>
</head>
<body ng-app="App">
<div ng-controller="formController">
<form name="myForm">
<input type="text" name="FirstName" ng-model="FN"/> <br>
<input type="text" name="LastName"/>
<br>
<input type="text" name="UserName"/>
<br>
<input type="password" name="Password"/>
</form>
<button ng-click="Clear()">Clear</button>
</div>
</body>
</html>
&#13;
这是我的示例,它对我有用,我正在使用angularjs 1.6