【发布时间】: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