AngularJS并获取控制器中的窗口滚动位置 [英] AngularJS and getting window scroll position in controller

查看:315
本文介绍了AngularJS并获取控制器中的窗口滚动位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在理解如何在控制器中获取窗口的滚动位置时遇到了一些麻烦,因此可以围绕它构建逻辑.

I'm having some trouble understanding how to get the scroll position of window within my controller, so I can build logic around it.

从我一直在阅读的所有问题和答案中,最能被接受的答案似乎是写一条指令来计算滚动位置,将该指令粘贴在元素上,就是这样.

From all the questions and answers I've been reading the most accepted answer seems to be to write a directive that calculates the scroll position, stick that directive on an element, and that's it.

但是,当您想执行以下操作时:

However, when you want to do something along the lines of:

if (scrollY > 100 ){
  $scope.showMenu = true;
}

if (scrollY > 500) {
  $scope.showFooter = true;
}

这种方法似乎不起作用,因为无法从控制器访问指令中的计算位置.正确的角度"方式是什么,仍然可以从控制器执行稍微复杂的逻辑?

This approach doesn't seem to work, because the calculated position in the directive can't be accessed from the controller. What would be the right 'Angular' way of doing this, which would still allow slightly more complicated logic to be executed from the controller?

推荐答案

根据@RobKohr注释,这是一种优化的方法,使用.on('scroll')$scope.$apply来更新滚动条上的作用域元素.

According to @RobKohr comment, here's a optimized approach using .on('scroll') and $scope.$apply to update a scope element on scroll.

$document.on('scroll', function() {
    // do your things like logging the Y-axis
    console.log($window.scrollY);

    // or pass this to the scope
    $scope.$apply(function() {
        $scope.pixelsScrolled = $window.scrollY;
    })
});

这篇关于AngularJS并获取控制器中的窗口滚动位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆