2017-05-21 73 views
2

如何在AngularJS指令中的元素上綁定滾動事件?我試圖在$ window上綁定滾動條,但現在我需要將它改爲這個類「.body-wrapper」(angular.element(document.queryselector(.body-wrapper))不起作用)。如何在AngularJS指令中的元素上綁定滾動事件

任何想法?

angular.element($window).bind("scroll", function() { 
    ... 
}) 

回答

5

沒有理由它不應該工作。

這個簡單的例子說明它does-

var app = angular.module('plunker', []); 
app.controller('MainCtrl', function($scope) { 
    angular.element(document.querySelector('.myDiv')).bind('scroll', function(){ 
     alert('scrolling is cool!'); 
    }) 
}); 

Plunker example

如果由於某種原因,它不能正常工作,後全部代碼。經過討論

編輯:

最終的問題是與「滾動」的具體事件,它可能與其他事件的碰撞。

更改事件爲「鼠標滾輪」做了伎倆。

Working fiddle

+0

謝謝,但我怎樣才能在指令中使用它? ('scroll',function(){ alert('scrolling is cool!'); });不工作 –

+0

「.ngscroll-container」是否在指令的html模板中? –

+0

它從另一個角度指令(自定義滾動條) –

6

您通常會爲此做出新的指示。

app.directive('scroll', [function() { 
    return { 
    link: function (scope, elem, attrs) { 
     elem.on('scroll', function (e) { 
     // do your thing 
     }); 
    }) 
    } 
}]); 

現在,在任何需要添加滾動事件的地方使用此指令。

<div class='.body-wrapper' scroll></div> 

指令是preferrd和清潔器的方法來訪問在Angularjs DOM元素,而不是angular.element

+0

這樣也不錯,但我有一些問題。 ..在主要指令im中已經使用了另一個elem。我可以使用2條指令,但它不是我認爲的最佳方式:/ –

+0

您可以詳細說明嗎?在一個元素上有兩個指令,或者在另一個指令的模板內有指令不是問題。您可能已經以這種方式使用其他指令(如ngClick,ngHref)。 – squgeim

+0

請檢查此[jsfiddle](https://jsfiddle.net/ar1mfeec/) –

4

滾輪事件觸發滾動事件的窗口比滾動事件。

angular.element($window).bind('mousewheel', function() { 
    // enter code here 
} 
+0

應該接受答案! :) –

3

我已經找到了最徹底的方法是:

(function() { 
    angular 
    .module('yourAppName') 
    .directive('scrollDirective', ['$window', scrollDirective]) 

    function scrollDirective($window) { 
    return { 
     link: function (scope, element, attrs) { 
     var handler; 
     $window = angular.element($window); 

     handler = function() { 
      console.log('scrolling....') 
     }; 

     $window.on('scroll', handler); 
     } 
    }; 

    }; 

})(); 

那麼你可以使用它在你的HTML爲:

<div scroll-directive="">a long list goes here</div> 
相關問題