简体   繁体   English

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

[英]How to handle this in Angular 1.5 component in callback function?

I am trying to refactor a 1.4 AngularJS directive to a 1.5 component. 我试图将1.4 AngularJS指令重构为1.5组件。 I try this by removing the $scope, and replacing it with this . 我通过删除$范围,并用它替换这试试this

It works fine so far, except: I need to set a $scope variable inside a callback function. 到目前为止,它工作正常,除了:我需要在回调函数中设置$scope变量。 Like this: 像这样:

this.variable = {};

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

But, this is undefined inside the callback function. 但是, this在回调函数中是未定义的。

How could a workaround or a proper way of setting the value of this.variable look like? 如何设置此this.variable的值的变通办法或正确的方式呢?

You need to assign the scope to your function: 您需要将范围分配给您的函数:

this.variable = {};

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

the this inside your function , refers to the funtion itself , that is why you get undefined. this自己的函数中,指的是funtion本身,这就是为什么你得到了一个未定义。

change the global this.variable = {} to $scope.variable={} and call it inside the function. 将全局this.variable = {}更改为$scope.variable={}并在函数内部调用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM