0

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

Ariunbayar
  • 81
  • 6
  • Favor `$timeout` over `setTimeout`: http://stackoverflow.com/questions/19609796/what-advantage-is-there-in-using-the-timeout-in-angular-js-instead-of-window-se – Davin Tryon May 15 '14 at 09:47

2 Answers2

1

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

Community
  • 1
  • 1
pkozlowski.opensource
  • 117,202
  • 60
  • 326
  • 286
0

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.

jcubic
  • 61,973
  • 54
  • 229
  • 402
  • thanks. I had to write `socket.on('myevent', function(arg){$scope.$apply(function(){trigger_fn(arg)})})` for my [socket.io](http://socket.io) implementation. Any chance this could be simpler to read? – Ariunbayar May 15 '14 at 10:31
  • You can use `socket.on('myevent', ngWrap($scope, trigger_fn));` with function from my answer. – jcubic May 15 '14 at 11:36