10

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
        });

}
Steffi
  • 6,835
  • 25
  • 78
  • 123
  • There is nothing special in angular that does this. Unless you want to set the "hash" and then scroll to. http://stackoverflow.com/questions/17284005/scrollto-function-in-angularjs . Most people just do it the same way you would do `window.scrollTo` – Nix Apr 29 '14 at 12:57

3 Answers3

3

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.

Nix
  • 57,072
  • 29
  • 149
  • 198
  • 1
    this is basically what I want to do, and it works, except for some odd reason, the ng-class on the various fields fails..... (triggered using angular's pristine and valid vars on fields) – DrogoNevets Sep 01 '14 at 10:12
  • 2
    @DrogoNevets your ng-class fails, because $location.hash() triggers the page to reload, therefore the controller is reset and the form is in its pristine state again. Took me hours to figure that out in my code – dube Aug 18 '15 at 12:44
0

I have a written a angularJS directive for the same purpose, you can include the directive as bower component and use this functionality without having to write any extra code for any form in your application. Please do let me know, if any improvements or corrections/enhancements are needed for the directive.

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

Thanks,

0

You could try something like this:

//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');
grindking
  • 917
  • 5
  • 13
  • 29