如何向下滚动到ng repeat中的最新条目(AngularJS或Javascript)
我有一个带有ng repeat的div来显示帖子,还有一个输入框来输入新帖子。对它们进行排序,以便在底部显示最新的帖子。添加新帖子后,我想向下滚动查看最新的帖子。有没有一个角度技巧可以有效地做到这一点?或者我需要使用javascript来实现期望的结果吗如何向下滚动到ng repeat中的最新条目(AngularJS或Javascript),javascript,jquery,html,css,angularjs,Javascript,Jquery,Html,Css,Angularjs,我有一个带有ng repeat的div来显示帖子,还有一个输入框来输入新帖子。对它们进行排序,以便在底部显示最新的帖子。添加新帖子后,我想向下滚动查看最新的帖子。有没有一个角度技巧可以有效地做到这一点?或者我需要使用javascript来实现期望的结果吗 <div ng-repeat="post in posts | limitTo:-15"> {{post.uid}} : {{post.text}} </div> <form> <inpu
<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>
{{post.uid}:{{post.text}
如果我理解你的要求,你一定可以使用JavaScript来实现这个功能。我建议,根据您的代码和用户单击submit时发生的情况,您可以捕获提交过程中需要完成的操作,然后向下滚动到最新的帖子。不确定如何处理提交功能,因此很难向您展示。但也许是这样的:
基本上,您可以拥有处理提交的所有代码,然后当用户确实单击它时,您可以使用如下方式滚动到底部:
$("#submit").on("click" ,function(){
scrolled=scrolled + 2700;
/* other functions here */
$(".stuff").animate({
scrollTop: scrolled
});
});
您可以通过添加装饰指令来实现这一通用性 下面是一个可能有助于您实现这一点的示例 基本上,当添加新项目时,$anchorScroll服务将用于滚动到该特定元素
因此,我通过正确使用anchorScroll(参考)找到了解决方案。代码如下:
<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> <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>
一两行JavaScript并没有那么糟糕?非常感谢。我试过了,当用户点击一个属性时,它就起作用了。我尝试了ng init和ang change,但都不起作用。如何自动包含它?我已经找到了解决方案。基本上,我尽量不将ui逻辑添加到控制器中;这是一种反模式。这是一个完美的指令用例;这也是他们存在的原因之一,和我写的一样。如果你告诉我什么地方不管用,我可以帮你
.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();
};
}])