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
. How can I access this
inside the function?
The context of this
inside the event handler is not the controller...it is window
since that is what $window
references
Try storing reference of controller this
in variable and using that inside the event handler.
Your issue is common problem using this
in javascript so storing reference is always a good practice
(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);
});
}]);
})();
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.