0
votes

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

2
Favor $timeout over setTimeout: stackoverflow.com/questions/19609796/… - Davin Tryon

2 Answers

1
votes
0
votes

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.