簡體   English   中英

AngularJS:使用$ animate在滾動條上隱藏元素

[英]AngularJS: Hide element on scroll with $animate

我有以下指令:

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");
            }
        });
    };
});

有時我在日志中都有“這被解雇”消息

另外,我有以下動畫服務:

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()或由jqLit​​e / jQuery方法on ,並bind執行,你需要手動觸發消化循環,讓角知道事情有了變化。

您可以使用$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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM