0

我刚刚开始使用新版本的 Laravel angular。我试图在向下滚动页面时添加一些代码来更改 rootScope 变量。这就是我到目前为止所拥有的。

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

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

问题是 this.$rootScope 在 angular.element 中未定义。我已经尝试在 angular.element 之外分配 this.$rootScope 以便它可以在绑定函数内部使用,但是数据绑定似乎确实有效。任何建议将不胜感激。如果答案很明显,请原谅我对 angular 1.5 和 ECMA6 很陌生。

4

1 回答 1

0

有一种更好的方法可以使用新的 ES6 lambda=>语法来设置 this 的词法值。更改代码以使用 lambda,如下所示,您将获得正确的值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;
    }
  });
}

的值在类的其他方法中按this词法设置正确,constructor但在类的其他方法中没有。所以你需要改变所有你使用的方法来=>获得正确的词法值

于 2016-05-27T12:31:42.120 回答