ohboy21
ohboy21

Reputation: 4319

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. I try this by removing the $scope, and replacing it with this.

It works fine so far, except: I need to set a $scope variable inside a callback function. Like this:

this.variable = {};

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

But, this is undefined inside the callback function.

How could a workaround or a proper way of setting the value of this.variable look like?

Upvotes: 0

Views: 237

Answers (2)

Theo Itzaris
Theo Itzaris

Reputation: 4671

the this inside your function , refers to the funtion itself , that is why you get undefined.

change the global this.variable = {} to $scope.variable={} and call it inside the function.

Upvotes: 0

AndreFeijo
AndreFeijo

Reputation: 10629

You need to assign the scope to your function:

this.variable = {};

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

Upvotes: 3

Related Questions