when $digest cycle is called?

前端 未结 3 1377
面向向阳花
面向向阳花 2020-12-01 10:43

I\'m very confused when a digest cycle is happening, is it called periodically based on a timer every 50ms (as it says here and implied here) or is it called after every eve

相关标签:
3条回答
  • 2020-12-01 11:18

    The digest process is kicked-in when any of the following occur as part of angular context:

    • DOM Events (like ng-click etc.)
    • Ajax with callbacks ($http etc.)
    • Timers with callbacks ($timeout etc.)
    • calling $apply, $digest
    • etc.

    It is important to note that the normal browser related DOM events (onclick etc.) and setTimeout would not trigger a digest process as they work out of "Angular Context".

    I learnt the above from the following:

    The above is a quick snapshot from a very in-depth tutorial available here: https://www.youtube.com/watch?v=SYuc1oSjhgY

    0 讨论(0)
  • 2020-12-01 11:20

    Any AngularJS scope variable when handled from outside (including ajax) needs a $apply().

    setTimeout is Javascript function So $apply is needed to update angularjs values.

    $timeout is a angularjs function which returns promise and takes care of the current scope and runs in the same digest cycle.

    So need not of $apply() function to update values.

    0 讨论(0)
  • 2020-12-01 11:30

    I think the description of the digest cycle at http://blog.bguiz.com/post/60397801810/digest-cycles-in-single-page-apps that it is

    code that runs at an interval

    is very misleading, and to be honest, when referring to Angular, I would even say wrong. To quote Pawel Kozlowski, Mastering Web Application Development with AngularJS

    AngularJS does not use any kind of polling mechanism to periodically check for model changes

    To prove there is no polling, if you have a template of

    <p>{{state}}</p>
    

    and controller code of

    $scope.state = 'Initial';
    // Deliberately *not* using $timeout here
    $window.setTimeout(function() {
      $scope.state = 'Changed';
    },1000);
    

    as in this plunker, then the string shown to the user will remain as Initial and never change to Changed.

    If you're wondering why you often see calls to $apply, but not always, it is probably because the various directives that come with Angular, such as ngClick or ngChange will call $apply themselves, which will then trigger the cycle. Event listeners to native JS events directly will not do this, so they will have to deliberately call $apply to have any changes made reflected in templates.

    0 讨论(0)
提交回复
热议问题