AngularJS指令滚动到给定项目 [英] AngularJS directive to scroll to a given item
问题描述
我有一个范围变量$ scope.first_unread_id,它在我的控制器中定义.在我的模板中,我有:
I have a scope variable $scope.first_unread_id which is defined in my controller. In my template, I have:
<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);
}
}
});
它有效,但是,有两个问题:
it works, however, two questions:
-
与询问范围相比,有没有更好的方法可以将"first_unread_id"从控制器范围内移到直接范围内?这似乎有点棘手".我希望我可以将它作为唯一的参数传递给直接对象,而不必在任何li元素上重复.
Is there a better way of getting the "first_unread_id" off the controller scope into the direct than interrogating scope.$parent? This seems a bit 'icky'. I was hoping I could pass that through the view to the direct as a parameter w/o having to repeat that on ever li element.
是否有更好的方法来避免需要setTimeout()调用?没有它,它有时会起作用 -我想是由于布局时间的差异.我了解我所使用的语法是定义链接功能-但我不清楚默认情况下该链接是前置链接还是后置链接-甚至对我的问题来说也很重要.
Is there a better way to avoid the need of the setTimeout() call? Without it, it works sometimes - I imagine due to difference in timing of layout. I understand the syntax I have used is defining a link function - but it isn't clear to me if that is a pre or post-link by default - and if that even matters for my issue.
推荐答案
- 您不需要作用域.$ parent-因为它将从父作用域继承该值,并且当它在父作用域中更改时,它将被向下传递.
- 默认为后链接功能.您是否有一些图像或加载的东西会在初始加载后不久使页面布局发生变化?您是否尝试了没有时间的setTimeout,例如setTimeout(function(){})?这样可以确保在所有其他操作完成之后都可以执行.
- 我还将稍微更改您的指令的逻辑以使其更通用.如果给定条件为真,我将其滚动到该元素.
这是这三个变化:
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', function () {
return function (scope, element, attributes) {
setTimeout(function () {
if (scope.$eval(attributes.scrollIf)) {
window.scrollTo(0, element[0].offsetTop - 100)
}
});
}
});
这篇关于AngularJS指令滚动到给定项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!