Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll to error in form?

I have just started using AngularJS, I would like to know this approach to scroll the page to the first input with an error when I submit a form.

Here is the way with jQuery :

    $('html, body').animate({
        scrollTop: $("--- #ID OF THE FIRST INPUT WITH ERROR ---").offset().top
    }, 2000);

How to do this in 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
        });

}
like image 306
Steffi Avatar asked Apr 29 '14 12:04

Steffi


1 Answers

You could use the $anchorScroll service.

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

Or you could just use:

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

There are a couple plugins out there that say they can do it.. but I unfortunately have not vetted them so I can't recommend any.

like image 56
Nix Avatar answered Oct 03 '22 08:10

Nix