How can I prevent observers from drawing in the same synthesis cycle?


I want to call a function drawChart() when either my string chartTitle or when any of the properties in my object chartOptions changes.

Watching them individually is easy:

$scope.$watch('chartTitle', drawChart);
$scope.$watchCollection('chartOptions', drawChart);

However, I need a way to combine them into one $watch statement (without adding chartTitle as a property of chartOptions.

How can I prevent both of these watchers from firing in the same digest cycle. That is, if I change both chartTitle and a property on chartOptions, how can I prevent drawChart from being called twice?

Possible approaches:

  • Do a deep watch on chartOptions and chartTitle. Unfortunately chartOptions is an extremely large and complicated object, so doing a deep watch on these properties is infeasible. Is it possible to put a limit on how deep to go?

  • Detect in the chartOptions watcher whether chartTitle has been changed during this digest cycle, and vice versa. Is this even possible?

  • Figure out a watch expression that would capture all the properties on chartOptions and chartTitle.

You can make a deep watch:

    function() {
        return {
            chartTitle: $scope.chartTitle,
            chartOptions: $scope.chartOptions
    function(newval) {
    true // deep watch

Keep an eye for performance problems, it will be creating an object each digest cycle. Normally it won't matter, but for a heavyweight application it might.