onkami
onkami

Reputation: 9431

Setting $watch to scope variables causes watch code to execute immediately, how to avoid?

I have an angularjs code like this:

 // some procedure called on page load...

 rectLayout(svg, scope.xdim, scope.ydim, scope.numOrder);
 // Watch changes of relevant variables:  if any of basic variables changed, redraw the whole thing.
 scope.$watch(['xdim', 'dimY', 'numOrder'], function () {
      rectLayout(svg, scope.xdim, scope.ydim, scope.numOrder);
 }, true);

This code causes rectLayout to be called twice in a row. I would need that $watch working later, but during initialization of page I only want first call to happen. How I can achieve that?

Upvotes: 0

Views: 55

Answers (1)

Robert Balicki
Robert Balicki

Reputation: 1633

You want to do the following:

scope.$watch(['xdim','dimY', 'numOrder'], function(newVal, oldVal) {
  if (newVal !== oldVal) {
    rectLayout(svg, newVal.xdim, newVal.ydim, newVal.numOrder);
  }
});

I'm not sure, by the way, that newVal is a hash and not an array. You should double check that, but in any case, that's the general pattern.

Upvotes: 1

Related Questions