2015-02-24 44 views
0

我有以下指令:

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的元素檢查員看到,DIV沒有得到後「$ animate.addClass新類(元,「褪色」)'被解僱

我失蹤了什麼?

回答

2

當通過例如addEventListener()或jqLit​​e/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

+0

給這名男子金牌^^ – 2015-02-24 22:22:23