【问题标题】:How to handle this in Angular 1.5 component in callback function?如何在回调函数的 Angular 1.5 组件中处理这个问题?
【发布时间】:2016-03-10 08:22:28
【问题描述】:

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

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

this.variable = {};

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

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

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

【问题讨论】:

标签: javascript angularjs


【解决方案1】:

您需要将范围分配给您的函数:

this.variable = {};

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

【讨论】:

    【解决方案2】:

    函数内部的 this 指的是 funtion 本身,这就是你得到未定义的原因。

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

    【讨论】:

    • 我想删除所有 $scopes,因为新的 1.5 组件语法。
    • 没有问题,我希望我能弄清楚为什么你的外部“this”在函数内部不起作用。
    猜你喜欢
    • 1970-01-01
    • 2017-01-16
    • 2016-09-04
    • 2017-12-18
    • 2016-10-03
    • 2020-09-01
    • 2018-02-25
    • 1970-01-01
    • 2016-08-21
    相关资源
    最近更新 更多