如何在回调函数的 Angular 1.5 组件中处理这个问题

How to handle this in Angular 1.5 component in callback function?

本文关键字:组件 处理 问题 回调 函数 Angular      更新时间:2023-09-26

我正在尝试将1.4 AngularJS指令重构为1.5组件。我通过删除$scope并将其替换为this来尝试此操作。

到目前为止它工作正常,除了:我需要在回调函数中设置一个$scope变量。喜欢这个:

this.variable = {};
someFunction().then(function(newValue) {
  this.variable = newValue;
});

但是,this在回调函数中是未定义的。

设置this.variable值的解决方法或正确方法是什么样子的?

您需要将作用域分配给函数:

this.variable = {};
someFunction().then(function(newValue) {
  this.variable = newValue;
}.bind(this));
函数

内部的this,指的是funtion本身,这就是为什么你得到未定义。

将全局this.variable = {}更改为 $scope.variable={} 并在函数中调用它。