【问题标题】:How to scroll down to latest entry in ng-repeat (AngularJS or Javascript)如何向下滚动到 ng-repeat 中的最新条目(AngularJS 或 Javascript)
【发布时间】:2015-02-07 16:20:57
【问题描述】:

我有一个带有 ng-repeat 的 div 来显示帖子和一个输入框来输入新帖子。它们被排序,最新的帖子显示在底部。添加新帖子后,我想向下滚动以查看最新帖子。是否有一个角度技巧可以有效地做到这一点?还是我需要使用 javascript 来达到预期的效果?

<div ng-repeat="post in posts | limitTo:-15">
    {{post.uid}} : {{post.text}}
</div>

<form>
  <input type="textarea" class="chatbox" placeholder="Start typing..." ng-model="newPost"/>
  <button class="chatbutton" type="submit" ng-click="addPost(newPost); newPost = null; setInterval();"><span class="glyphicon glyphicon-send"></span></button>
</form>

【问题讨论】:

标签: javascript jquery html css angularjs


【解决方案1】:

您可以通过添加装饰指令来使其通用。

这里有一个例子可能对你有所帮助;

基本上,当添加新项目时,$anchorScroll 服务将用于滚动到该特定元素。

http://jsbin.com/binoqavopa/18/edit

【解决方案2】:

如果我理解您的要求,您肯定可以使用 JavaScript 来实现此功能。我建议根据您的代码以及用户单击提交时发生的情况,您可以捕获提交过程所需完成的操作,然后向下滚动到最新帖子。不确定您如何处理提交功能,因此很难向您展示。但也许是这样的:

基本上,您可以拥有处理提交的所有代码,然后当用户单击它时,您可以使用以下内容滚动到底部:

 $("#submit").on("click" ,function(){
            scrolled=scrolled + 2700;
            /* other functions here */
            $(".stuff").animate({
                    scrollTop:  scrolled
               });

 });

【讨论】:

    【解决方案3】:

    所以我通过正确使用anchorScroll找到了解决方案(参考PSL)。代码如下:

    <div id="scrollArea" ng-controller="ScrollController">
    
      <div style="padding: 10px" ng-repeat="post in posts | limitTo:-10">
        <span class="chatbox" style="background: {{post.pcolor}}">{{post.text}}</span>&nbsp;&nbsp;<span class="chatname">{{post.pname}} ({{post.time}})</span>
      </div>
    
    <form>
      <input  class="chatinput" placeholder="Start typing..." ng-model="newPost"/>
      <button class="chatbutton" type="submit" ng-click="gotoBottom(); addPost(newPost); newPost = null;"><span class="glyphicon glyphicon-send"></span></button>
    </form>
    <a id="bottom"></a>
    </div>
    

    请务必在 ScrollController 的 div 中添加 id="bottom":

    .controller('ScrollController', ['$scope', '$location', '$anchorScroll',
      function ($scope, $location, $anchorScroll) {
        $scope.gotoBottom = function() {
          // set the location.hash to the id of
          // the element you wish to scroll to.
          $location.hash('bottom');
    
          // call $anchorScroll()
          $anchorScroll();
        };
      }])
    

    【讨论】:

    • 尽量不要在你的控制器中添加 ui 逻辑;这是一种反模式。这是指令的完美用例;这就是它们存在的原因之一
    • 和我写的一样。如果你告诉我什么不正确,我可以帮助你
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多