Crisiiii
Crisiiii

Reputation: 409

No update data after timeout in AngularJS

I have a doubt about the binding in AngularJS. This is an example of my code:

.controller("user", function(){
    this.test = 'hi!';
    this.getCourseSeriesProducts = function(){          
        setTimeout(function(){
            alert(this.test);
            this.test = 'bye';
            alert(this.test);
        },3000);
    }
});

The question is, in the first alert after the setTimeout, the result is undefined, but in theory should have the 'hi!' value. So, when I change the result to alert 'bye', the value on screen doesn't change and still being 'hi!'. What's happening?

Upvotes: 0

Views: 41

Answers (2)

Komo
Komo

Reputation: 2138

Be careful with the usage of the this keyword. In your function this.getCourseSeriesProducts, the context has changed so this doesn't refer to the same context as when this.test was first defined. I suggest putting a few console.log(this) to understand.

Upvotes: 2

sylwester
sylwester

Reputation: 16498

Please see demo below, use angular $timeout instead setTimeout and you need to call function to executed it.

var app = angular.module('app', []);

app.controller('homeCtrl', function($scope, $timeout) {

  var test = 'hi!';

  this.getCourseSeriesProducts = function() {

    $timeout(function() {
      alert(test);
      test = 'bye';
      alert(test);
    }, 300);
  }

  this.getCourseSeriesProducts();


});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
  <div ng-controller="homeCtrl">


  </div>
</div>

Upvotes: 0

Related Questions