Angular 在滚动时更改变量

Angular change var on scroll

我的 $scope 中有一个变量,我需要在向上滚动时减小它,在向下滚动时增大它。我怎样才能做到这一点?我应该使用 js 滚动吗?有什么方法可以不重新发明轮子吗?

你的问题不清楚,但如果我理解正确的话你想increase/decrease基于滚动方向的计数器。

您可以通过点击 'scroll'(jQuery) 事件,例如:

angular.element($window).on('scroll', function(event) {
    // Do something here.
});

最好你可以编写一个自定义指令来处理这个并发出自定义事件,然后你可以在你的控制器中监听这个事件并根据它采取行动。

注意:您还可以对滚动事件进行去抖动。

P.S。 : 请始终提供代码片段或 jsfiddle/codepen,以便其他人可以更好地理解您的问题。

angular.module('app', [])
  .controller('MainController', function($rootScope, $scope) {
    var changeBy = 5;
    $scope.scrollCounter = 0;

    // Tap into custom 'scrollHappened' event.
    $rootScope.$on('scrollHappened', function(event, scrollUpHappened) {

      // If the scroll direction is 'down'.
      if (scrollUpHappened) {
        $scope.scrollCounter += changeBy;
      } else { // Scroll direction is 'up'.
        $scope.scrollCounter -= changeBy;
      }
    });
  })
  .directive('scrollCounter', function($rootScope, $window) {
    return {
      restrict: 'A',
      link: function() {
        var lastScrollPos = 0;

        // Add a scroll event on $window object.
        angular.element($window).on('scroll', function(event) {
        console.log(angular.element(event.target))
          var scrollPos = angular.element(event.target).scrollTop();

          // Emit custom 'scrollHappened' event.
          $rootScope.$emit('scrollHappened', (scrollPos > lastScrollPos));

          // As all this is happening outside of the angular world
          // wrap the update logic inside $apply, so that update will
          // be visible to the angular.
          $rootScope.$apply(function() {
            lastScrollPos = scrollPos;
          });
        });
      }
    }
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script>

<div data-ng-app="app" data-ng-controller="MainController">

  <div scroll-counter="" style="height: 400px">
    <span>Current scroll counter = {{ scrollCounter }}</span>
    <br/><br/>
    <span>Current scroll counter = {{ scrollCounter }}</span>
    <br/><br/>
    <span>Current scroll counter = {{ scrollCounter }}</span>
    <br/><br/>
    <span>Current scroll counter = {{ scrollCounter }}</span>
    <br/><br/>
    <span>Current scroll counter = {{ scrollCounter }}</span>
    <br/><br/>
    <span>Current scroll counter = {{ scrollCounter }}</span>
    <br/><br/>
  </div>

</div>