AngularJS:使用$animate隐藏滚动中的元素

AngularJS: Hide element on scroll with $animate

本文关键字:滚动 元素 隐藏 animate 使用 AngularJS      更新时间:2024-04-20

我有以下指令:

angular.module('mymod').directive("hideOnScroll", function($animate, $document) {
    return function(scope, element, attrs) {
        $document.bind('scroll', function () {
            if ($document.scrollTop() > 80) {
                console.log("this is fired1")
                $animate.addClass(element, "fade");
            } else {
                console.log("this is fired2")
                $animate.removeClass(element, "fade");
            }
        });
    };
});

在的某个时刻,我在日志中有两条"this is fired"消息

另外,我有以下动画服务:

angular.module('mymod').animation(".fade", function() {
    console.log("this is never fired3")
    return {
        addClass: function(element, className) {
            console.log("this is never fired4")
            //TweenMax.to(element, 1, {opacity: 0});
        },
        removeClass: function(element, className) {
            console.log("this is never fired5")
            //TweenMax.to(element, 1, {opacity: 1});
        }
    };
});

它的控制台消息都没有被触发。完全(3、4和5)。我检查了它是否被添加到浏览器中,是的。我有ngAnimate作为依赖

这就是要素:

<div hide-on-scroll>Hello</div>

编辑:我可以在chrome的元素检查器中看到,在'$animate.addClass(element,"fade")'被激发后,div没有得到新的类

我错过了什么?

当由addEventListener()或由jqLite/jQuery方法onbind手动附加的事件处理程序执行时,您需要手动触发摘要循环,让Angular知道发生了变化。

您可以使用$apply(例如ng-click在内部使用):

$document.bind('scroll', function() {
  scope.$apply(function() {
    if ($document.scrollTop() > 80) {
      console.log("this is fired1");
      $animate.addClass(element, "fade");
    } else {
      console.log("this is fired2");
      $animate.removeClass(element, "fade");
    }
  });
});

还要注意,当您将事件侦听器附加到文档时,您应该在作用域被破坏时手动删除它们:

var onScroll = function() {
  scope.$apply(function() {
    if ($document.scrollTop() > 80) {
      console.log("this is fired1");
      $animate.addClass(element, "fade");
    } else {
      console.log("this is fired2");
      $animate.removeClass(element, "fade");
    }
  });
};
$document.bind('scroll', onScroll);
scope.$on('$destroy', function() {
  $document.unbind('scroll', onScroll);
});

演示:http://plnkr.co/edit/wl0vujSnBcb24FHGQ4il?p=preview