angular.scope.$apply

Description

$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.

Life cycle

Pseudo-Code of $apply()

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

Scope's $apply() method transitions through the following stages:

  1. The expression is executed using the $eval() method.
  2. Any exceptions from the execution of the expression are forwarded to the $exceptionHandler service.
  3. The watch listeners are fired immediately after the expression was executed using the $digest() method.

Usage

angular.scope.$apply([exp]);

Parameters

Returns

{*}

The result of evaluating the expression.