Monday, 22 June 2015

Understanding Angular’s $apply() and $digest()

{{xxxx}} in html will create a watcher to watch "xxxx"'s change.

when you change this model --- "xxxx" in controller, actually you called angular's build-in function, and this function calls $apply() which will can $digest() and it launchs a digest cycle.

in a digest cycle, system will exam all watchers in the scope and check if the model value is changed and then apply the change by "fn" function in the watcher (you can debug $scope to see that). Then if the "fn" function change another model, it will tiger the digest cycle again, and it will exam all watchers agin. (So, you potentially can have an endlessly looping.... but that will be stopped after 10 times)

one thing worth to note:

$scope.$apply() will call $rootScope.$apply() and it will all $digest() on &rootScope and that will tiger all $scopes to digest.

So, if you change value of model($scope's variables) from out of angular context e.g. jquery or timeout(), your binding system will doesn't work, because it doesn't aware the change because nobody called the $apply() function, so you should manually call it.

No comments:

Post a comment