Scrolling to specific element on different template after clicking link (Angularjs)

99封情书 提交于 2019-12-20 05:43:28

问题


Hey guys I am pretty new to Angular.

Users can edit profile settings in profileSettings page.

I have the following on my profile template:

<div>{{ user.name }}</div>
<a class="pull-right" ui-sref="profileSettings"><strong>Edit Name</strong></a>
...more code...
<div>{{ user.description }}</div>
<a class="pull-right" ui-sref="profileSettings"><strong>Edit Description</strong></a>

I want them to be able to click on the edit link that takes them to the Settingsprofile template. However I want when the new template renders to automatically scroll to the relevant field.

So if they click edit link for name, they are taken to the profileSettings template and automatically scrolled to edit name field. If they click the edit description link then they are also redirected to profileSettings page but automatically scrolled to edit description field.

Is there an easy way to do this with Angualar/ui-sref?


回答1:


Use the optional onEnter callback which will be called when profileSettings state becomes active to render those two functions :

  • $location.hash('hashValue') will take to the element with id="hashValue" url like : /profileSettings.html#hashValue
  • $anchorScroll will scrolls to that element

So your code may look like this:

$stateProvider.state('profileSettings', {
  url: '/settings',
  template: 'settings.html',
  controller: 'ProfileSettingsCtrl',
  onEnter: function(){
      $location.hash('hashValue');
      $anchorScroll();
  }
});

Note: Remember to add $location and $anchorScrollto your dependencies.



来源:https://stackoverflow.com/questions/31620412/scrolling-to-specific-element-on-different-template-after-clicking-link-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!