AngularJS:何时在'scroll'事件中使用$ apply [英] AngularJS: when to use $apply in a 'scroll' event
本文介绍了AngularJS:何时在'scroll'事件中使用$ apply的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一条通过以下方式添加固定"类的指令:
I have a directive that adds 'fixed' class by:
ng-class='{ "fixed": fixed }'
指令具有以下功能:
angular.element($window)
.on('scroll', function() {
if (this.pageYOffset >= 480) {
if (!scope.fixed) {
scope.fixed = true;
scope.$apply();
}
} else {
if (scope.fixed) {
scope.fixed = false;
scope.$apply();
}
}
});
我的问题是,是否应该像这样应用 scope.$ apply()
,所以它仅在变量更改时才触发,或者只写就行:
My question is, should I apply the scope.$apply()
like this, so it only fires whenever my variable changes, or is it ok just to write:
angular.element($window)
.on('scroll', function() {
if (this.pageYOffset >= 480) {
scope.fixed = true;
} else {
scope.fixed = false;
}
scope.$apply();
});
也许我不知道使用 scope.$ watch
的某些用途?
Maybe there's some use of scope.$watch
that I am unaware of?
推荐答案
如果未进行更新,则调用 scope.$ apply()
没有意义.因此,我建议您使用第一种方法:
It doesn't make sense to call scope.$apply()
if no update is made. So I would suggest use your first approach which is :
angular.element($window)
.on('scroll', function() {
if (this.pageYOffset >= 480) {
if (!scope.fixed) {
scope.fixed = true;
scope.$apply();
}
} else {
if (scope.fixed) {
scope.fixed = false;
scope.$apply();
}
}
});
这篇关于AngularJS:何时在'scroll'事件中使用$ apply的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文