0

I'm trying to understand how is handled the view updating in Angular. When I use a native asynchronous function and it callback updates a $scope variable, the view is not updated. But when I use an Angular asynchronous function, the view is updated properly. For example:

// Example 1: This code updates the store in view
$timeout(function() {
    $scope.store = {
        name: 'MyName'
    }
}, 2000);

// Example 2: This code does not update the store in view
setTimeout(function () {
    $scope.store = {
        name: 'MyName'
    }
}, 2000);

Why the second example does not update the store?

5
  • 2
    Because the second example has no idea what a digest cycle is and doesnt update it (hence the reason certain native functions are converted). Commented Dec 9, 2014 at 22:16
  • possible duplicate of The view is not updated in AngularJS Commented Dec 9, 2014 at 22:23
  • How can I wrap a native asynchronous function in order to achieve the view update? I don't want use $scope.apply(). Commented Dec 9, 2014 at 22:24
  • 2
    Without going into Angular's core you must use $apply to get your $scope changes registered. Why would you not want to use this? Commented Dec 9, 2014 at 22:28
  • Because I'm making a custom ORM using Dexie and its api is asynchronous. Commented Dec 9, 2014 at 22:33

1 Answer 1

2

This is because the Angular service $timeout is aware of the Angular runtime and will register the change properly.

The same behavior can be captured with vanilla js by calling $apply() on the scope after you make your changes:

setTimeout(function () {
  $scope.store = {
    name: 'MyName'
  }
  $scope.$apply();
}, 2000);

There are other services like $window and $interval that act as convenience wrappers to regular JS but they make sure any $scope changes get registered to the digest cycle correctly.

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

Comments

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.