Ariunbayar
Ariunbayar

Reputation: 81

AngularJS value won't change with setTimeout

I wanted to change a scope variable after the page has been initialized. I have a angular application with following code:

$scope.names = ['Jack'];
append_name = function(){$scope.names.push('Bob');}
setTimeout(append_name, 2000);

Tough I don't see the value change after the specified delay. Here is the plunker http://plnkr.co/edit/FBa2fwb7js8pRNENNJof

Upvotes: 0

Views: 278

Answers (2)

jcubic
jcubic

Reputation: 66650

If you create code outside of angular you need to tell that you change something with $apply

$scope.names = ['Jack'];
append_name = function() {
   $scope.$apply(function() {
      $scope.names.push('Bob');
   });
};
setTimeout(append_name, 2000);

You can create handy higher order function to wrap your functions with $apply:

function ngWrap($scope, fn) {
    return function() {
        var args = [].slice.call(arguments);
        if ($scope.$$phase) {
            fn.apply(null, args);
        } else {
            return $scope.$apply(function() {
                fn.apply(null, args);
            });
        }
    };
}

this can be used like:

setTimeout(ngWrap($scope, function() {
    $scope.names.push('Bob');
}), 2000);

Also angular have $timeout that will handle this.

Upvotes: 0

pkozlowski.opensource
pkozlowski.opensource

Reputation: 117370

Short answer: use the built-in $timeout service instead of setTimeout: http://plnkr.co/edit/nh1jEhocRpXtD0rUTh4k?p=preview

Long answer is here: https://stackoverflow.com/a/9693933/1418796

Upvotes: 1

Related Questions