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?

  • 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). – tymeJV Dec 09 '14 at 22:16
  • possible duplicate of [The view is not updated in AngularJS](http://stackoverflow.com/questions/10179488/the-view-is-not-updated-in-angularjs) – PSL Dec 09 '14 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(). – Danilo Aburto Vivians Dec 09 '14 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? – tommybananas Dec 09 '14 at 22:28
  • Because I'm making a custom ORM using [Dexie](http://dexie.org/) and its api is asynchronous. – Danilo Aburto Vivians Dec 09 '14 at 22:33

1 Answers1

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.

tommybananas
  • 5,718
  • 1
  • 28
  • 48