[英]Multiple directives for the same module in angular
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. 当滚动到达页面底部进行无限分页时,将触发一个(whenScrolled)。 The other (fromTop) triggers either a "top" or "bottom" that can be used to hide/show a "go to top" link on the page.
另一个(fromTop)触发“顶部”或“底部”,可用于隐藏/显示页面上的“转到顶部”链接。 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.
似乎“ whenScrolled”指令正在覆盖“ fromTop”,并且fromTop永远不会被调用。 However, if I delete "whenScrolled", "fromTop" gets called just fine.
但是,如果我删除“ whenScrolled”,那么“ fromTop”就可以了。 Why is this?
为什么是这样?
This has nothing to do with angular.js at all. 这与angular.js完全无关。
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. 您的问题:每次将指令附加到DOM元素时,都会覆盖
window.onscroll
函数,其结果是只有最后一个应用的指令才起作用。 There can only be one onscroll
function. 只能有一个
onscroll
功能。
You need to work around this limitation some how: 您需要通过以下方法解决此限制:
onscroll
and then propagate the changes to all your directives. onscroll
,然后将更改传播到所有指令。 bind
function which does the same. bind
函数,它的功能相同。 As option 2.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.