天道酬勤,学无止境

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

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?

评论

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.

受限制的 HTML

  • 允许的HTML标签:<a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd> <h2 id> <h3 id> <h4 id> <h5 id> <h6 id>
  • 自动断行和分段。
  • 网页和电子邮件地址自动转换为链接。

相关推荐