0

I've just started using the new version of Laravel angular. I'm trying to add some code to change a rootScope variable when scrolling down the page. this is what i have so far.

$onInit(){
    this.$rootScope.showTestBanner = true;
    var $rootScope = this.$rootScope;

    angular.element(this.$window).bind("scroll", function() {
        if (this.pageYOffset >= 20) {
            this.$rootScope.showTestBanner = false;
        }
    });
}

The problem is that this.$rootScope is undefined inside the angular.element. Ive tried assigning this.$rootScope outside angular.element so it can be used inside the bind function but then the databinding does seem to work. Any suggestions would be much appreciated. If the answer is obvious please excuse me i'm very new to angular 1.5 and ECMA6.

1 Answers1

0

There is a better way to set the lexical value of this using the new ES6 lambda => syntax. Change your code to use lambda as below and you will get the correct value of this:

$onInit = () => {
  this.$rootScope.showTestBanner = true;
  let $rootScope = this.$rootScope;

  angular.element(this.$window).bind("scroll", function() {
    if (this.pageYOffset >= 20) {
        this.$rootScope.showTestBanner = false;
    }
  });
}

The value of this is lexically set correctly within the constructor but not in other methods on the class. So you need to change all you methods to use => to have correct lexical value of this

Aditya Singh
  • 15,810
  • 15
  • 45
  • 67
  • The arrow syntax should be in the scroll handler, not the `$onInit` function (which presumably works fine if the scroll is being called) – CodingIntrigue May 27 '16 at 13:15