31

I am trying to scroll to an element on the page after I 'show' it. I.E. i have a very long list of users and I display them as a list. Each element has an edit icon you can click. On click I show the user form which is at the top of the page. I then want to scroll to that location.

  // helper method to scroll
  $scope.scrollTo = function (id) {
    $location.hash(id);
    $anchorScroll();
  }

On edit user click:

  $scope.editUser = function (user) {
    $scope.user = user; // set user
    $scope.setShowUserForm(true); // show edit form
    $scope.scrollTo('admin-form'); // scroll to the form
  }

This works great except for the first time. I checked the DOM and my 'user-form' element is in the DOM but hidden, which is what I want. When I click on an edit user the first time the scroll does not work. After the first time it fails everything is fine. I am not sure what changed.

I also set the form to show by default such that I knew it was in the DOM and visible the first time I click edit. That did not solve my problem either. So whether its in the DOM or not, hidden or not the first scroll to fails.

Any idea what I am doing wrong?

Edit:

I think I know what is going on but I have no idea how to solve it. I am using routing in my application. I have routes like:

/#/main /#/admin

Its my admin page that I am using the scroll to that is causing problems. Here is the html I want to scroll to:

<div id="admin-form">
...
</div>

The problem is when I use angular to scroll it changes my url to:

/#/admin#admin-form

When is does that it seems to hit the route controller and reload my admin page which is why the scroll does not happen. once I am on the /#/admin#admin-form url the scroll to works because angular does not see a change in my route and does not reload the page. But if I change my url back to /#/admin and click the button that performs the scroll to angular again changes the url to /#/admin#admin-form.

I am sure this is as expected but I have no idea how to fix it. Or if I can.

4

5 に答える 5

9

特定の要素までスクロールしたい場合、URL を更新して目的の ID を表示することに興味がないことがわかりました (例: www.something.com/#admin-form の #admin-form id)

したがって、URL を更新せずにスクロールするには、ロケーション ハッシュを更新する必要なく、anchorscroll を呼び出すだけでよいことがわかりました。

$anchorScroll('admin-form');
于 2015-07-19T19:38:50.090 に答える
2

この問題を誇示するためにプランクを作成しました。メッセージを表示するには、ボタンを 2 回クリックする必要があることに注意してください。

http://plnkr.co/edit/oU3REYC2upvlPMc5ipBp?p=preview

于 2013-07-22T23:17:19.533 に答える