How to trace source of $watch model updates in AngularJS?

Viewed 2913

In my multi-user AngularJS app, I have a model object on my scope. This model can be manipulated by both user input and server updates.

I have a $watch observer to track the model and update the UI. Is it possible to determine the source/reason of my model update from within my $watch function? Without that check, I have problems with feedback loops (e.g. UI→Server→UI).

UPDATE: some code

Controller:

$scope.elementProperties = { left: 0 };

$scope.$watch('elementProperties.left', function(newVal, oldVal) { changeSelectedElementProperty('left', newVal, oldVal); } );

Directive:

angular.module('myapp.ui-editor').directive('myappPropertiesPanel', function () {
    return {
        templateUrl: 'views/ui-editor/myappPropertiesPanel.html',
        restrict: 'A',
        scope: { elementProperties: '=' },

        link: function postLink (scope, element, attrs) {
            scope.$watch('elementProperties.left', function(newVal, oldVal) { console.log('PropertiesPanel change left', newVal, oldVal); } );
        }
    };
});
3 Answers

"Is it possible to determine the source/reason of my model update from within my $watch function?"

The short answer is no, it is not possible to know the source of the change as the change is not marked at the time of change but rather on the following digest when the watcher tests oldWatchedValue === newWatchedValue and discovers that it fails the equality check. So there is nothing to bind the fact that there was a change to the source of the change.

Related