When does the digest get triggered in AngularJS -
all:
i got question how angularjs data digest monitor changing of scope data, example:
<button ng-click="changename()">{{name}}</button>
and data change function like:
$scope.name = "change name"; $scope.changename = function(){ $scope.name = "name1"; $scope.name = "name2"; } $scope.$watch("name", function(newname, oldname){ if(newname!=oldname){ console.log("new: "+newname, "old: "+oldname); } });
this changename function change scope.name twice in row, watcher can only catch change "change name" "name2" ( console print "new: name2 old: change name")
could confirm guess digest cycle start after function block finish executing?
thanks
i want correct answer rbaghbanli
misleading.
indeed, because javascript single threaded, happen when click on button is:
the variable `$scope.name` set "name1"; variable `$scope.name` set "name2"; > end of execution stack angular runs $digest cycle $watchers executed since watcher value has changed, angular runs $digest cycle $watchers executed watcher have same value, end of $digest cycle > end of execution stack
so no watcher nor happen when within same function, until end of every line of function.
the reason why angular runs digest cycle after changename
call because within ng-click
directive, , angular built-in directive, code wrapped inside $scope.$apply
call. read ng-click
following code (even if technically not this):
element.on('click', function() { $scope.changename(); $rootscope.$digest(); });
note: wanted simplify generic idea, technically true, angular executes $digest cycle right after code (as can see in pseudo ng-click
), within same execution stack. means settimeout
or other asynchronous call happen after digest cycle , after dom has been updated latest changes, can useful sometimes.
Comments
Post a Comment