$ anchorScroll在AngularJs

时间:2015-09-04 12:44:03

标签: angularjs anchor-scroll

我正在开发一个提交表单的应用程序,并从服务器获取结果,然后是HTML表格视图。我的输入形式有点大,覆盖整个屏幕。当表格出现时,我想在表格视图中自动向下滚动。我使用了来自angularJs的$ anchorScroll。但我无法达到我想要的结果。我还使用$ timeout确保表已经存在,然后执行$ anchorScroll,但仍然没有成功。 (基于此解决方案:Using $location and $anchorScroll to scroll a table row into view

听到我的代码。

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>

控制器

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

});

我不知道为什么它不起作用?

我是否需要在CSS中定义id scrollArea和resultTable?

任何帮助将不胜感激。 提前谢谢。

更新

基于Okazari的解决方案,我尝试在HTML的最底部添加另一个带有许多br标签的div。现在,当我刷新页面时,它会自动滚动到该div标签而不单击“开始”。这有点奇怪。我也试图覆盖

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

标记另一个div标签,其id =&#34; resultTable&#34;。 但它仍然没有用。

1 个答案:

答案 0 :(得分:3)

您实际上是在没有任何参数的情况下调用您的函数

ng-click="searchCtrl.gotoTable()"

而在您的控制器中,您希望有一个:

self.gotoTable = function(resultTable)

尝试这样的事情

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

或者这个:

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

(只有一个,而不是两个)

希望它有所帮助。

编辑:很确定你不能去隐藏的div。正如我在评论中所说,当您尝试使用anchorscroll()时,您的ng-show可能会被评估为真。

这是一个没有ng-show的工作plunker。我将构建一个小解决方案来避免ng-show问题。

为了避免这种副作用,我用另一个div包装了ng-show的div。

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