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

1

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

2 Comments

thanks. I had to write socket.on('myevent', function(arg){$scope.$apply(function(){trigger_fn(arg)})}) for my socket.io implementation. Any chance this could be simpler to read?
You can use socket.on('myevent', ngWrap($scope, trigger_fn)); with function from my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.