Reputation: 57
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
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