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?