0

I've built a directive that gets its data by $parse'ing from an Angular expression in one of my $attrs. The expression is typically a simple filter applied to a list model, the evaluation of which will change when the parent $scope is modified.

To monitor when it should update the data it's using, my directive is using a $scope.$watch call, with a custom function that re-$parse's the expression. The problem I'm running into is that $parse will generate a new object instance from the expression, so $watch sees the value as changed even when the data in each object is completely equivalent. This results in my code hitting the $digest iteration cap very quickly due to actions taken in the $watch callback.

To get around this I am doing the following, currently:

 var getter = $parse($attrs.myExpression);
 $scope.$watch(function () {
    var newVal = getter($scope);
    if (JSON.stringify($scope.currentData) !== JSON.stringify(newVal)) {
      return newVal;
    } else {
      return $scope.currentData;
    }
  }, function (newVal) {
    $scope.currentData = newVal;
    // other stuff
  });

However, I don't like relying on JSON as an intermediary here, nor using my $watch'ed function itself to evaluate equivalency of old and new values. Is there a flag the $watch can take to determine if two objects are equivalent, or is there a better approach for handling this kind of situation?

cmw
  • 855
  • 7
  • 17

1 Answers1

4

Hi you should use this,

scope.$watch('data', function (newVal) { /*...*/ }, true);

This has been answerd here on stackoverflow

Community
  • 1
  • 1
hjgraca
  • 1,695
  • 1
  • 14
  • 29
  • Just what I was looking for -- the optional deep compare argument. Thanks! – cmw Oct 06 '13 at 21:22
  • No problem, had the same question the first time I came across this. Just don't forget to mark has the answer to help others. Thanks – hjgraca Oct 06 '13 at 21:40