0
$scope.runTest = function() {
    var statesArray = ['Running', 'Complete', 'Rejected'];
    var rand = statesArray[Math.floor(Math.random() * statesArray.length)];
    item.state = 'Running';
    console.log(rand)
    window.setTimeout(function() {
        item.state = rand;
    }, 6000);
};

item state change to Running is successful, but after that state won't change to a random as stated in the window.setTimeout function.

Where am I wrong here?

knitevision
  • 3,023
  • 6
  • 29
  • 44

3 Answers3

3

you should use angular's $timeout service

$timeout(function() {
    item.state = rand;
}, 6000);
ivcandela
  • 331
  • 3
  • 12
2

Windows.setTimeout is out side an angular scope

you have to use $scope.$apply() to bind that value.

or use $timeout

refer this What advantage is there in using the $timeout in Angular JS instead of window.setTimeout?

Community
  • 1
  • 1
gaurav bhavsar
  • 2,033
  • 2
  • 22
  • 36
2

You can use setTimeout or $timeout, the problem here is that you are forgetting to call scope.apply() when using setTimeout to ensure that any changes to the scope will be reflected elsewhere.

setTimeout(function () {
    $scope.$apply(function () {
        item.state = rand;
    });
}, 6000);

If you use $timeout you don't need to use $scope.$apply():

$timeout(function() {
    item.state = rand;
}, 6000);

For more info regarding these two concepts, take a look at What advantage is there in using the $timeout in Angular JS instead of window.setTimeout?.

Community
  • 1
  • 1
pgrodrigues
  • 2,083
  • 1
  • 24
  • 28