【问题标题】:How to scroll to error in form?如何滚动到表单中的错误?
【发布时间】:2014-06-15 10:07:31
【问题描述】:

我刚开始使用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
        });

}

【问题讨论】:

  • 在 Angular 中没有什么特别之处可以做到这一点。除非你想设置“哈希”然后滚动到。 stackoverflow.com/questions/17284005/… 。大多数人只是按照你会做的同样的方式window.scrollTo

标签: forms angularjs angularjs-scope


【解决方案1】:

我为相同的目的编写了一个 angularJS 指令,您可以将该指令包含为 bower 组件并使用此功能,而无需为您的应用程序中的任何表单编写任何额外的代码。如果指令需要任何改进或更正/增强,请告诉我。

https://github.com/udayvarala/ng-scroll-to-error

谢谢,

【讨论】:

    【解决方案2】:

    你可以试试这样的:

    //scroll to an anchor by ID
    $scope.scrollToAnchor = function (anchor) {
       if (anchor !== null) {
           $location.hash(anchor);
           $anchorScroll(anchor);
       }
    }
    
    //use above function
    $scope.scrollToAnchor($scope.myForm.$error.required[0].$name);
    
    //or any ID
    $scope.scrollToAnchor('ID');
    

    【讨论】:

      【解决方案3】:

      您可以使用$anchorScroll 服务。

      $location.hash("<errorFieldID>");
      $anchorScroll();  
      

      或者你可以使用:

      $window.scrollTo  //you could even get bold and user window.scrollTo
      

      有几个插件说他们可以做到。但不幸的是我没有审查它们,所以我不能推荐任何。

      【讨论】:

      • 这基本上是我想要做的,它可以工作,除了一些奇怪的原因,各个字段上的 ng-class 失败.....(使用 angular 的原始和有效变量触发字段)
      • @DrogoNevets 您的 ng-class 失败,因为 $location.hash() 触发页面重新加载,因此控制器被重置并且表单再次处于原始状态。我花了几个小时在我的代码中弄清楚这一点
      猜你喜欢
      • 2012-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-28
      • 2015-07-29
      • 1970-01-01
      • 2014-08-10
      相关资源
      最近更新 更多