user2942970
user2942970

Reputation: 57

Angular 1.58 Component $timeout does not apply changes

I have come across a problem when converting my code to use components. In the components controller I use a $timeout function to delay the update of a object. This works in a normal controller, but not within the component - the code is very simply:

this.settime = function(){
  this.showDisplay = {hide:true};
  $timeout(function() {
    this.showDisplay= {hide:false};
  }, 2000);
};

The problem is that the updated value does not get passed to the DOM, in this example $ctrl.showDisplay.hide gets set to true, but after the timeout is completed it does not go back to false. I have tried using $scope.$apply(); to force the update but it has no affect.

Upvotes: 2

Views: 498

Answers (1)

Pankaj Parkar
Pankaj Parkar

Reputation: 136154

this you are referring to inside $timeout function is different than context which is there inside controller. While changing hide property of showDisplay object, you don't need to change the reference of the object, you could directly change the property.

var self = this;
self.settime = function(){
  self.showDisplay = {hide:true};
  $timeout(function() {
    self.showDisplay.hide = false;
  }, 2000);
};

ES6 Version

this.settime = function(){
  this.showDisplay = {hide:true};
  $timeout(() => {
    this.showDisplay.hide = false;
  }, 2000);
};

Upvotes: 3

Related Questions