[英]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()
或由jqLite / 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);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.