我刚刚开始使用 AngularJS,我想知道这种在提交表单时将页面滚动到第一个输入并出现错误的方法。
这是使用 jQuery 的方法:
$('html, body').animate({
scrollTop: $("--- #ID OF THE FIRST INPUT WITH ERROR ---").offset().top
}, 2000);
如何在 Angular 中做到这一点?
HTML
<form class="form" novalidate>
<input type="text" class="nom-du-projet" ng-model="fields.nom" required />
<p ng-show="fields.nom.$invalid && !fields.nom.$pristine">The name is required.</p>
<input type="text" ng-model="fields.cible" />
...
<button type="submit" ng-click="submit(fields)">Add</button>
</form>
JS
$scope.submit = function(fields){
console.log(fields);
$http
.post('/xxxx', fields)
.success(function(response) {
// success
})
.error(function(response) {
// scroll to field error
});
}
最佳答案
您可以使用 $anchorScroll
服务。
$location.hash("<errorFieldID>");
$anchorScroll();
或者你可以只使用:
$window.scrollTo //you could even get bold and user window.scrollTo
有几个插件说他们可以做到......但不幸的是我没有审查它们所以我不能推荐任何。
关于forms - 如何滚动到表单中的错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23365185/