加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

AngularJS指令滚动到给定项目

发布时间:2020-12-17 07:55:40 所属栏目:安全 来源:网络整理
导读:我有一个范围变量$scope.first_unread_id,它在我的控制器中定义.在我的模板中,我有: div id="items" ul class="standard-list" li ng-repeat="item in items" scroll-to-id="first_unread_id" span class="content"{{ item.content }}/span /li /ul/div 我
我有一个范围变量$scope.first_unread_id,它在我的控制器中定义.在我的模板中,我有:
<div id="items" >
  <ul class="standard-list">
    <li ng-repeat="item in items" scroll-to-id="first_unread_id">
    <span class="content">{{ item.content }}</span>
    </li>
  </ul>
</div>

我的指令看起来像:

angular.module('ScrollToId',[]).
directive('scrollToId',function () {
  return function (scope,element,attributes) {
    var id = scope.$parent[attributes["scrollToId"]];
    if (id === scope.item.id) {
      setTimeout(function () {
        window.scrollTo(0,element[0].offsetTop - 100)
      },20);
    }
  }

});

然而,它有两个问题:

>是否有更好的方法可以将“first_unread_id”从控制器范围中移除到直接询问范围内.$parent?这看起来有点’icky’.我希望我可以通过视图将其传递给直接作为参数,而不必在ever元素上重复该参数.
>有没有更好的方法来避免需要setTimeout()调用?没有它,它有时会起作用 – 我想是由于布局时间的不同.我理解我使用的语法是定义一个链接函数 – 但是我不清楚这是默认情况下的前置链接还是后置链接 – 如果这对我的问题也很重要.

>您不应该使用范围.$parent – 因为它将继承父作用域中的值,并且当它在父作用域中发生更改时,它将被传递下去.
>默认为后链接功能.您是否有一些图像或某些加载会使页面布局在初始加载后立即更改?您是否尝试过没有时间的setTimeout,例如setTimeout(function(){})?这将确保这将“一个接一个”其他一切完成.
>我还会稍微改变指令的逻辑,使其更通用.如果给定条件为真,我会滚动到元素.

以下是这3个变化:

HTML:

<div id="items" >
  <ul class="standard-list">
    <li ng-repeat="item in items" scroll-if="item.id == first_unread_id">
      <span class="content">{{ item.content }}</span>
    </li>
  </ul>
</div>

JS:

app.directive('scrollIf',attributes) {
    setTimeout(function () {
      if (scope.$eval(attributes.scrollIf)) {
        window.scrollTo(0,element[0].offsetTop - 100)
      }
    });
  }
});

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读