【问题标题】:angularjs anchor in iterator (anchorscroll, ng-repeat,loop)迭代器中的 angularjs 锚(anchorscroll,ng-repeat,loop)
【发布时间】:2013-11-21 12:58:05
【问题描述】:

例如,

<div ng-repeat="item in items">
   <p>item.title</p>
    ...
    ...
    ...
   <p>item.up</p>
</div>

据我所知,锚滚动需要为锚指定一个 id,但是我如何在没有 id 的情况下进行锚滚动,情况是有另一个循环包装这个项目重复。而且我不能指定像

这样的ID
<div ng-repeat="item in items">
   <p id="anchor{{$index}}">item.title</p>
    ...
    ...
    ...
   <p>item.up</p>
</div>

所以如果代码如下,就会有multi id="anchor{{$index}}"

 <div ng-repeat="parent in parents">
    <div ng-repeat="item in items">
       <p id="anchor{{$index}}">item.title</p>
      ........
    </div>
</div>

而且我不想用两个索引来指定id,不然代码会太复杂。

我该如何解决它.....谢谢

【问题讨论】:

    标签: javascript jquery node.js angularjs


    【解决方案1】:

    在不知道您的确切情况的情况下,我会说您将不得不在您关心的元素上人为地创建某种独特的anchorId

    同样,我不知道您的控制器或模型是什么样的,但您可以使用与此类似的技术。

    angular.forEach(this.parents, function(parent, i){
        //Add unique anchorId to parent
        parent.anchorId = "anchor-" + i;
        angular.forEach(parent.children, function(child, j){
    
           //Add anchorId to child as well
           child.anchorId = "anchor-" + i + "-" + j;
        });
    });
    

    这基本上会给你一些你可以在 DOM 中绑定的东西,然后通过点击事件触发滚动。绑定将类似于您上面的绑定。

    <div data-ng-repeat="parent in ctrl.parents">
       <h1 id="{{parent.anchorId}}">{{parent.name}}</h1>
       <div data-ng-repeat="child in parent.children">
          <h2 id="{{child.anchorId}}" class="child">
             {{child.name}}
             <small>
                <a href="" ng-click="ctrl.scrollTo(parent.anchorId)">
                 | to {{parent.name}}
                </a>
             </small>
          </h2>
       </div>
    </div>
    

    最后,您可以在您的控制器中创建一个看起来像这样的scrollTo 方法。

    Ctrl.prototype.scrollTo = function(anchorId){
      this.$location.hash(anchorId);
      this.$anchorScroll();
    };
    

    这基本上会做你想做的事,并让你滚动到你心中的内容。

    我已将所有这些都包含在 jsFiddle example 中,以便您查看完整的工作示例。

    【讨论】:

    • 嗨 Josh,正如你所说,我们必须使用这两个索引来指定 id 吗?没有其他解决方案?
    • @Awakening - 我并不是说没有其他方法。只是你需要一些独特的方式来识别一个元素。这只是实现这一目标的一种可能方式。
    • 嗨,Josh,你遇到过这个问题吗,我正在使用 ng-view,例如localhost:8000/main.html#/events,正如你所看到的,/events 是路由,当我使用 $anchorscorll () id, url 会像“localhost:8000/main.html#/events#anchorId-0-3-2”,有时我的页面会重新加载(意味着重新做路由),如何防止这种情况,我只想锚滚动,重新加载太愚蠢了
    • @Awakening - 如果你想在不改变路线的情况下滚动到一个 id,那么你应该只使用一个普通的 &lt;a href="#anchor01"&gt; 并完全跳过 $anchorScroll() 调用。
    猜你喜欢
    • 1970-01-01
    • 2012-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-14
    • 2017-12-22
    • 1970-01-01
    相关资源
    最近更新 更多