[英]How can I access this in angular($window).bind()?
I am trying to perfom an action when a user scrolls, however I am unable to access the scope of the controller. 我正在尝试在用户滚动时执行一个操作,但是我无法访问控制器的范围。
My code is: 我的代码是:
(function() {
angular.module("myApp")
.controller("MyController", ['$window', function($window){
this.sidebarFixed = false;
angular.element($window).bind("scroll", function() {
console.log(this.sidebarFixed);
});
}]);
})();
The output of this is undefined
. 此输出
undefined
。 How can I access this
inside the function? 我如何在函数内部访问
this
?
The context of this
inside the event handler is not the controller...it is window
since that is what $window
references 的情况下
this
事件处理程序是不针对控制器...它是window
,因为这是$window
引用
Try storing reference of controller this
in variable and using that inside the event handler. 尝试存储控制器的参考
this
在变量和使用该事件处理程序的内部。
Your issue is common problem using this
in javascript so storing reference is always a good practice 您的问题是在javascript中使用
this
问题的常见问题,因此存储参考始终是一个好习惯
(function() {
angular.module("myApp")
.controller("MyController", ['$window', function($window){
var vm = this; // store reference then always use variable
vm.sidebarFixed = false;
angular.element($window).bind("scroll", function() {
// `this` is `window` here
console.log(vm.sidebarFixed);
});
}]);
})();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.