【问题标题】:AngularJS: why is $scope undefined inside my ES6 controller?AngularJS:为什么在我的 ES6 控制器中未定义 $scope?
【发布时间】:2018-05-13 15:46:27
【问题描述】:

我是 AngularJS 的新手,所以这个问题的答案可能很明显,但我一直坚持下去。

在我的组件中,我有以下代码(我已针对问题对其进行了简化):

class $controller {
  constructor($scope, Vote) {
    $scope.isRunning = false;
    this.Vote = Vote;
  }

  switchVote(user){
    $scope.isRunning = true;
    if (appUser.vote) {
      var vote = new this.Vote({userId: user.id});
      vote.delete().then(function() {
        user.vote = null;
        $scope.isRunning = false;
      })
    }
     else {
      this.componentThing.createVote(user).then(function(vote) {
        user.vote = vote.id;
        $scope.isRunning = false;
      })
    }
  }
}

在 HTML 中,我在按钮上有一个 ng-disabled="isRunning",它允许创建和销毁投票。这样做的目的是防止用户在ajax请求完成之前点击两次,从而防止多个请求堆积。

我的问题是 $scope 在我的 switchVote() 方法中未定义。为什么我在构造函数中初始化了它还是未定义?

【问题讨论】:

  • 我没有在 ES6 中使用过 AngularJS,但我认为你需要在构造函数中绑定作用域:this.$scope = $scope
  • 如果你使用的是 ES6 类,你应该避免使用 $scope 并使用controllerAs 语法来实例化控制器。
  • 也使用粗箭头函数代替旧式匿名函数。

标签: javascript angularjs ecmascript-6


【解决方案1】:

$scope 仅在构造函数中可见。您需要将其分配给 this 上的访问器,以便您可以在其他函数中访问它。

constructor($scope, Vote) {
   this.$scope = $scope;
   this.$scope.isRunning = true;
   ...
}

switchVote(user){
   this.$scope.isRunning = true;
   ...
}

【讨论】:

  • 这解决了我的问题!非常感谢!
猜你喜欢
  • 2023-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-18
  • 2015-04-02
  • 1970-01-01
相关资源
最近更新 更多