forms - 如何滚动到表单中的错误?

标签 forms angularjs angularjs-scope

我刚刚开始使用 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/

相关文章:

javascript - AngularJS 模块 : this versus $scope

forms - 以表格形式连续调用/评估?

php - 无法加载 localhost php 文件的源代码

javascript - 错误不会显示在以 html 形式提交的表单上的 span 标记中 - Jquery

angularjs - 如何根据条件动态注入(inject) Angular 1.5 组件?

javascript - 带索引的 Ng 样式

javascript - ng-model 未在嵌套指令中更新

javascript - 自定义服务返回未定义

php - 使用 php 和 mysql 的简单 html 表单。如何维护数据库中空字段的 NULL 值

javascript - 如何将 ui-grid 导出到 excel 文件?