要过滤的纳克重复元件的位置 [英] Going to the position of a filtered ng-repeat element
问题描述
我有基于在范围布尔瓦尔滤纳克重复元素的列表
I have a list of ng-repeat elements that are filtered based on boolean vars in scope.
HTML
<button ng-click="toggleSection(1)">Section 1</button>
<button ng-click="toggleSection(2)">Section 2</button>
<button ng-click="toggleSection(3)">Section 3</button>
<div id="$index" ng-repeat="section in sections track by $index | filterSections">
...
</div>
过滤器:
myApp.filter('filterSections', function() {
return function(input) {
var returnArray = [];
$.each(input, function(index, bool) {
if (bool) returnArray.push(bool);
});
return returnArray;
}
})
和在我的控制器:
$scope.sections = [false, false, false];
$scope.toggleSection = function(n) {
$scope.sections[n] = $scope.sections[n] ? false : true;
}
不过,我想同样的toggleSection功能转到元素的位置,这表明,像...
However, I want the same toggleSection function to go to the position of the element that it shows, like...
$scope.toggleSection = function(n) {
$scope.sections[n] = $scope.sections[n] ? false : true;
window.scrollTo($("#" + n).position().top, 0);
}
但我不能这样做,因为它需要时间DOM以显示它的创建部分。在此之前,元素(及其位置)不存在
But I can't do this because it takes time for the DOM to show the section that it's creating. Before that, the element (and its position) does not exist.
设置超时可能会工作,但似乎马虎。
Setting a timeout would probably work, but that seems sloppy.
我怀疑我需要建立某种形式的回调或承诺。是这样吗?
I suspect that I need to create some sort of callback or promise. Is that right?
推荐答案
自定义指令,承诺或其他任何东西,如果你的动作(滚动)依赖于DOM(和它),你不能避免以后的角度来执行它消化周期。
Custom directive, promise or anything else, if your action (scroll) relies on the DOM (and it does), you cannot avoid to execute it after an angular digest cycle.
因此,短期的方式来做到这确实是一个超时:
Hence the short way to do that is indeed with a timeout:
$scope.toggleSection = function(n) {
$scope.sections[n] = $scope.sections[n] ? false : true;
$timeout(function() {
window.scrollTo($("#" + n).position().top, 0);
}, 0, false);
}
请注意 $超时
是假的第三个参数:这是因为你不需要 $适用
的范围(再跑摘要周期)的超时执行其回调后,因为它是唯一的jQuery
Note the third argument of $timeout
being false: this is because you do not need to $apply
the scope (run another digest cycle) after the timeout execute its callback since it is jQuery only.
再次滚动DOM被更新的浏览器没有意义之前,所以你不能避免它(但你可以将其隐藏)。
Again, scrolling before the DOM is updated does not make sense for a browser, so you cannot avoid it (yet you can hide it).
这篇关于要过滤的纳克重复元件的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!