最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What does $scope.$apply() do? - Stack Overflow

programmeradmin3浏览0评论

I've been using $scope.$apply() to update the bindings for my models when I receive data through websockets in my Angular apps and it works. But what does it actually do and why does it need to be called to achieve the update?

I've been using $scope.$apply() to update the bindings for my models when I receive data through websockets in my Angular apps and it works. But what does it actually do and why does it need to be called to achieve the update?

Share Improve this question edited Sep 10, 2013 at 4:24 Dan Prince asked Sep 10, 2013 at 3:56 Dan PrinceDan Prince 30k14 gold badges93 silver badges123 bronze badges 1
  • This might help:: jimhoskins./2012/12/17/angularjs-and-apply.html – Sudhir Bastakoti Commented Sep 10, 2013 at 4:06
Add a ment  | 

3 Answers 3

Reset to default 8

If you call $apply the code provided will be executed in angular-context which you can make use of what angular provides.

From the link:

Angular modifies the normal JavaScript flow by providing its own event processing loop. This splits the JavaScript into classical and Angular execution context. Only operations which are applied in Angular execution context will benefit from Angular data-binding, exception handling, property watching, etc...

You can also use $apply() to enter Angular execution context from JavaScript. Keep in mind that in most places (controllers, services) $apply has already been called for you by the directive which is handling the event. An explicit call to $apply is needed only when implementing custom event callbacks, or when working with third-party library callbacks.

From the Angular docs:

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life-cycle of exception handling, executing watches.

The documentation also provides a pseudo-code of it:

function $apply(expr) {
  try {
    return $eval(expr);
  } catch (e) {
    $exceptionHandler(e);
  } finally {
    $root.$digest();
  }
}

In short, $apply evaluates an expression and triggers a digest cycle, making Angular execute all registered watch listeners and update any view bindings.

Finally, you've said that you've been using $apply to update the bindings for your models, but that is only required when the update es from outside Angular. In most cases you don't need to call it manually.

Simply put it:

  1. (Optionally) Processes an expression you pass to it as an argument.
  2. Calls $digest() on the $rootScope.

I also wrote a blog entry about what $apply, $digest and $watch do and how they work together

I hope that helps.

发布评论

评论列表(0)

  1. 暂无评论