$anchorScroll is not working in AngularJs

Harsh Soni picture Harsh Soni · Sep 4, 2015 · Viewed 11.5k times · Source

I am working on an app that submits the form and get the result from the server which followed by HTML table view. My input form is a bit big which covers whole the screen. When the table comes then I want automatically scroll down at the table view. I used $anchorScroll from angularJs. But I am not able to achieve the result what I want. I also used $timeout to make sure the table is already exist or not and then perform $anchorScroll, but still no success. (based on this solution : Using $location and $anchorScroll to scroll a table row into view

Hear is my code.

HTML

<div data-ng-controller="searchController as searchCtrl" id="scrollArea">
    <form>
       //HTML input elements

       <div class="buttons">
           <md-button class="md-primary md-raised" ng-click="searchCtrl.gotoTable('resultTable')">Start</md-button>
       </div>
    </form>
</div>

<!-- Smart Table for displaying result -->
<div class="rtable" ng-show = "searchCtrl.tableViewData.length > 0" id="resultTable">

//table content

</div>

Controller

angular.module('myApp')

.controller("searchController", function($log, searchService, $scope, $location, $anchorScroll, $timeout){
    var self = this;

 self.gotoTable = function(resultTable) 
    {
        $timeout(function() {
            $location.hash(resultTable);
            $anchorScroll();
        });
    };

});

I dont know why its not working?

Do i need to define the id scrollArea and resultTable in my CSS?

Any help would be appreciated. Thanks in advance.

UPDATE

Based on Okazari's solution, I tried to put a another div with many br tag above at the very bottom of my HTML. Now When I refresh the page then it automatically scroll to that div tag without clicking Start. this is a bit weird. I also tried to cover the

 <div class="rtable" ng-show = "searchCtrl.tableViewData.length > 0" id="resultTable">

tag with another div tag with id = "resultTable". But still it did not work.

Answer

Okazari picture Okazari · Sep 4, 2015

You actually are invoking your function without any parameters

ng-click="searchCtrl.gotoTable()"

whereas in your controller you expect to have one :

self.gotoTable = function(resultTable)

Try something like this

ng-click="searchCtrl.gotoTable('resultTable')"

or this :

self.gotoTable = function() 
{
    $timeout(function() {
        $location.hash("resultTable");
        $anchorScroll();
    });
};

(just one, not both)

Hope it helped.

EDIT : Pretty sure that you can't go to a hidden div. As i said in comment your ng-show may be evaluated to true when you try to anchorscroll().

Here is a working plunker without ng-show. I'll build a tiny solution to avoid the ng-show issue.

To avoid this side effect, i wrapped the div with ng-show with another div.

<div id="resultTable">
 <div class="rtable" ng-show = "searchCtrl.tableViewData.length > 0">
</div>