How does data binding work in AngularJS?

前端 未结 14 1517
情话喂你
情话喂你 2020-11-21 05:41

How does data binding work in the AngularJS framework?

I haven\'t found technical details on their site. It\'s more or less clear how it works when data

14条回答
  •  礼貌的吻别
    2020-11-21 06:01

    AngularJS handle data-binding mechanism with the help of three powerful functions : $watch(),$digest()and $apply(). Most of the time AngularJS will call the $scope.$watch() and $scope.$digest(), but in some cases you may have to call these functions manually to update with new values.

    $watch() :-

    This function is used to observe changes in a variable on the $scope. It accepts three parameters: expression, listener and equality object, where listener and equality object are optional parameters.

    $digest() -

    This function iterates through all the watches in the $scope object, and its child $scope objects
    (if it has any). When $digest() iterates over the watches, it checks if the value of the expression has changed. If the value has changed, AngularJS calls the listener with new value and old value. The $digest() function is called whenever AngularJS thinks it is necessary. For example, after a button click, or after an AJAX call. You may have some cases where AngularJS does not call the $digest() function for you. In that case you have to call it yourself.

    $apply() -

    Angular do auto-magically updates only those model changes which are inside AngularJS context. When you do change in any model outside of the Angular context (like browser DOM events, setTimeout, XHR or third party libraries), then you need to inform Angular of the changes by calling $apply() manually. When the $apply() function call finishes AngularJS calls $digest() internally, so all data bindings are updated.

提交回复
热议问题