60

当用户将浏览器窗口滚动到某个点以下时,我正在切换#page div 的类。

到目前为止我所做的工作正常:

http://jsfiddle.net/eTTZj/29/

<div ng-app="myApp" scroll id="page">

    <header></header>
    <section></section>

</div>

app = angular.module('myApp', []);
app.directive("scroll", function ($window) {
    return function(scope, element, attrs) {
        angular.element($window).bind("scroll", function() {
             if (this.pageYOffset >= 100) {
                 element.addClass('min');
                 console.log('Scrolled below header.');
             } else {
                 element.removeClass('min');
                 console.log('Header is in view.');
             }
        });
    };
});

(当他们在标题下方滚动窗口时,100px,类被切换)

虽然,如果我错了,请纠正我,但我觉得这不是使用 Angular 执行此操作的正确方法。

相反,我认为最好的方法是使用 ng-class 并在作用域中存储一个布尔值。像这样的东西:

<div ng-app="myApp" scroll id="page" ng-class="{min: boolChangeClass}">

    <header></header>
    <section></section>

</div>

app = angular.module('myApp', []);
app.directive("scroll", function ($window) {
    return function(scope, element, attrs) {
        angular.element($window).bind("scroll", function() {
             if (this.pageYOffset >= 100) {
                 scope.boolChangeClass = true;
                 console.log('Scrolled below header.');
             } else {
                 scope.boolChangeClass = false;
                 console.log('Header is in view.');
             }
        });
    };
});

虽然这不是动态的,但如果我在滚动回调中更改 scope.boolChangeClass 的值,那么 ng-class 不会更新。

所以我的问题是:当用户滚动到某个点以下时,如何最好地切换#page 的类,使用 AngularJS?

4

6 回答 6

86

感谢 Flek 在他的评论中回答我的问题:

http://jsfiddle.net/eTTZj/30/

<div ng-app="myApp" scroll id="page" ng-class="{min:boolChangeClass}">

    <header></header>
    <section></section>

</div>

app = angular.module('myApp', []);
app.directive("scroll", function ($window) {
    return function(scope, element, attrs) {
        angular.element($window).bind("scroll", function() {
             if (this.pageYOffset >= 100) {
                 scope.boolChangeClass = true;
             } else {
                 scope.boolChangeClass = false;
             }
            scope.$apply();
        });
    };
});
于 2013-02-14T17:43:42.307 回答
23

为什么你们都建议重范围操作?我不明白为什么这不是“角度”解决方案:

.directive('changeClassOnScroll', function ($window) {
  return {
    restrict: 'A',
    scope: {
        offset: "@",
        scrollClass: "@"
    },
    link: function(scope, element) {
        angular.element($window).bind("scroll", function() {
            if (this.pageYOffset >= parseInt(scope.offset)) {
                element.addClass(scope.scrollClass);
            } else {
                element.removeClass(scope.scrollClass);
            }
        });
    }
  };
})

所以你可以像这样使用它:

<navbar change-class-on-scroll offset="500" scroll-class="you-have-scrolled-down"></navbar>

或者

<div change-class-on-scroll offset="500" scroll-class="you-have-scrolled-down"></div>
于 2016-08-04T16:07:17.513 回答
16

这是我的解决方案,它不是那么棘手,并且允许您通过一个简单的 ng-class 指令将它用于多个标记。像这样,您可以为每种情况选择类和滚动位置。

你的 App.js :

angular.module('myApp',[])
    .controller('mainCtrl',function($window, $scope){
        $scope.scrollPos = 0;

        $window.onscroll = function(){
            $scope.scrollPos = document.body.scrollTop || document.documentElement.scrollTop || 0;
            $scope.$apply(); //or simply $scope.$digest();
        };
    });

你的 index.html :

<html ng-app="myApp">
    <head></head>
    <body>
        <section ng-controller="mainCtrl">
            <p class="red" ng-class="{fix:scrollPos >= 100}">fix me when scroll is equals to 100</p>
            <p class="blue" ng-class="{fix:scrollPos >= 150}">fix me when scroll is equals to 150</p>
        </section>
    </body>
</html>

在这里工作JSFiddle

编辑 :

正如$apply()实际调用一样$rootScope.$digest(),您可以直接使用$scope.$digest()而不是$scope.$apply()根据上下文获得更好的性能。
长话短说:$apply() 将始终有效,但会强制$digest所有可能导致性能问题的范围。

于 2015-07-06T16:02:00.473 回答
2

也许这可以帮助:)

控制器

$scope.scrollevent = function($e){
   // Your code
}

html

<div scroll scroll-event="scrollevent">//scrollable content</div>

或者

<body scroll scroll-event="scrollevent">//scrollable content</body>

指示

.directive("scroll", function ($window) {
   return {
      scope: {
         scrollEvent: '&'
      },
      link : function(scope, element, attrs) {
        $("#"+attrs.id).scroll(function($e) { scope.scrollEvent != null ?  scope.scrollEvent()($e) : null })
      }
   }
})
于 2016-01-21T13:00:16.170 回答
1

性能呢?

  1. 始终去抖动事件以减少计算
  2. 用于scope.applyAsync减少总的消化循环数
function debounce(func, wait) {
    var timeout;
    return function () {
        var context = this, args = arguments;
        var later = function () {
            timeout = null;
            func.apply(context, args);
        };

        if (!timeout) func.apply(context, args);
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

angular.module('app.layout')
  .directive('classScroll', function ($window) {    
    return {
        restrict: 'A',
        link: function (scope, element) {    
            function toggle() {
                angular.element(element)
                  .toggleClass('class-scroll--scrolled', 
                    window.pageYOffset > 0);
                scope.$applyAsync();
            }    
            angular.element($window)
              .on('scroll', debounce(toggle, 50));

            toggle();
        }
    };
});

3.如果您根本不需要触发观察者/摘要然后使用compile

.directive('classScroll', function ($window, utils) {
    return {
        restrict: 'A',
        compile: function (element, attributes) {
            function toggle() {
                angular.element(element)
                  .toggleClass(attributes.classScroll,
                    window.pageYOffset > 0);
            }

            angular.element($window)
              .on('scroll', utils.debounce(toggle, 50));
            toggle();
        }
    };
  });

你可以像这样使用它<header class-scroll="header--scrolled">

于 2016-10-30T01:52:37.617 回答
-4

正如他们所说,指令不在“角度世界之内”。因此,您必须在更改内容时使用 apply 重新进入它

于 2013-04-05T13:18:41.540 回答