AngularJS value won't change with setTimeout

I wanted to change the scope variable after the page was initialized. I have an angular application with the following code:

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

Hard, I do not see a change in value after the specified delay. Here is the plunker http://plnkr.co/edit/FBa2fwb7js8pRNENNJof

0
source share
2 answers

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

The long answer is here: fooobar.com/questions/580 / ...

+1
source

If you are creating code outside of angular, you need to say that you are changing something with $ apply

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

, $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);
            });
        }
    };
}

:

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

angular $timeout, .

0

All Articles