1

What does $scope.apply do? In some cases, if $scope.apply() is not present, $scope.watch() is not triggered. For example,

The controller has the following:

setTimeout(function(){
  $scope.person = someperson;
}, 500);

person is being watched in the directive.

$scope.watch('person', function(){
  console.log($scope.person);
  $scope.apply();
});

In this case, watch is triggered only when apply is there.

xxxxx
  • 1,918
  • 2
  • 17
  • 22

3 Answers3

1

If you modify an AngularJS model outside (from external JavaScript) - you should use $scope.$apply() to let AngularJS know that model has changed. In your example you use setTimeout() which is an async external js method. However if you use the AngularJS $timeout you wont need to call $scope.$apply().

John
  • 1,268
  • 16
  • 25
Petr Averyanov
  • 9,327
  • 3
  • 20
  • 38
1

$scope.apply() will trigger the $digest loop of AngularJS. To put is simple, it's just a convenient way to trigger the app rerender.

Usually it is used when you want to run a piece of code that is outside of angular app.

Direct from the documentation:

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

Example of using scope.$apply() with jQuery Datepicker:

angular.module('customApp', []).directive('datepicker', function () {
    return {
        require: 'ngModel',
         link: function (scope, element, attrs, ngModelCtrl) {
            jQuery(element).datepicker({
                onSelect: function (date) {
                    scope.myDate = date;
                    scope.$apply();
                }
            });
        }
    };
});
Rise Ledger
  • 949
  • 7
  • 11
0

setTimeout(function(){}:-It is javascript function which is out of the scope of anuglar js you need to manually apply the digest cycle with the help of $scope.apply();

But instead you can use $timeout service which is more angular way.

squiroid
  • 13,809
  • 6
  • 47
  • 67