I've created a module for my angular app, and I have two similar directives that I have associated with both.
One (whenScrolled) is triggered when the scroll reaches the bottom of the page for infinite pagination. The other (fromTop) triggers either a "top" or "bottom" that can be used to hide/show a "go to top" link on the page. This is how I have them set up:
angular.module('scroll', []).directive('fromTop', function() {
return function(scope, element, attributes) {
var raw = element[0]
var scrollDistance = Math.round(window.outerHeight)
window.onscroll = function() {
console.log(window.pageYOffset, raw.scrollHeight + scrollDistance)
if (window.pageYOffset >= raw.scrollHeight + scrollDistance) {
scope.position = 'bottom'
scope.$apply(attributes.fromTop)
} else {
scope.position = 'top'
scope.$apply(attributes.fromTop)
}
}
}
}).directive('whenScrolled', function() {
return function(scope, element, attributes) {
var raw = element[0]
var scrollDistance = Math.round(window.outerHeight)
window.onscroll = function() {
//console.log(window.pageYOffset, raw.scrollHeight - scrollDistance)
if (window.pageYOffset >= raw.scrollHeight - scrollDistance) {
scope.$apply(attributes.whenScrolled)
}
}
}
});
Unfortunately, this isn't working. it seems that the "whenScrolled" directive is overwriting the "fromTop" one and fromTop never gets called. However, if I delete "whenScrolled", "fromTop" gets called just fine. Why is this?
This has nothing to do with angular.js at all.
Your problem: You overwrite the window.onscroll
function every time you attach a directive to a DOM element, which has the effect that only the last of you applied directives will work. There can only be one onscroll
function.
You need to work around this limitation some how:
onscroll
and then propagate the changes to all your directives. bind
function which does the same. As option 2.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.