点击链接后滚动到不同模板上的特定元素(Angularjs)

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

本文关键字:元素 Angularjs 链接 滚动      更新时间:2023-09-26

大家好,我是Angular的新手。

用户可以在profilessettings页面编辑配置文件设置。

我的个人资料模板上有以下内容:

<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>

我希望他们能够点击将他们带到Settingsprofile模板的编辑链接。然而,我想当新的模板渲染自动滚动到相关的字段。

因此,如果他们点击编辑链接的名称,他们被带到profilessettings模板,并自动滚动到编辑名称字段。如果他们点击编辑描述链接,那么他们也会被重定向到profilessettings页面,但会自动滚动到编辑描述字段。

在angalar/ui-sref中是否有一个简单的方法来做到这一点?

使用可选的onEnter当 profilessettings state变为活动状态以呈现这两个函数时将调用的回调:

  • location.hash美元("hashValue")将取id="hashValue"元素 url like : /profileSettings.html#hashValue
  • anchorScroll美元将滚动到该元素
所以你的代码可能是这样的:
$stateProvider.state('profileSettings', {
  url: '/settings',
  template: 'settings.html',
  controller: 'ProfileSettingsCtrl',
  onEnter: function(){
      $location.hash('hashValue');
      $anchorScroll();
  }
});

注意:请记住将$location$anchorScroll添加到您的依赖项