Monday, February 29, 2016

AngularJS: Change in Underlying Model Not Reflected in View


Struggling with an update to the view model that among other things affects the visibility of a DOM element. While the DOM element became visible, some of its properties where not updated. The DOM properties that were not updated include offset.top and offset.left. They were always zero even after the DOM element became visible.

This is perhaps because updating the DOM properties is not instantaneous but rather does take time. What comes to mind is the question of what if you force update to propagate?

So $scope.$apply will indirectly cause watchers of the model's properties to be notified of changes. $scope.$apply internally calls $digest and the documentation does not recommend calling $digest directly.

Therefore calling $scope.$apply seemingly fixes the issue. It, however, does not seem a recommended practice. See discussion here http://stackoverflow.com/questions/12729122/angularjs-prevent-error-digest-already-in-progress-when-calling-scope-apply

In my case what worked is waiting for the DOM to updated. The amount of time wait was chosen based on experimentation. The way to wait is using setTimeout or in the angular way $timeout.