tomvo tomvo - 1 month ago 6
Javascript Question

Angular $watch array and update from server

I'm deep watching an array called

$scope.route.waypoints
using the following:

$scope.$watch('route.waypoints', _.debounce(function (prev, cur) {
if(!$scope.initialized) return;
$scope.saveRoute(true);
console.log('route waypoints DEEP check');
}, 500), true)


in my
saveRoute
method I
PUT
the collection to the server.

What I want to do is upon return from the server I want to update some properties in my waypoints collection again. But when I update using the following:

if(data.linked && data.linked.waypoints.length){
$scope.route.waypoints = data.linked.waypoints;
}else{
$scope.route.waypoints = [];
}

$scope.route.days = data.routes[0].days;


the $watch is called again and the whole thing starts over again.
How can I avoid that? I tried using $scope flags but it seems they are ignored again. it's all a bit of a mess now...

Answer

Ok I solved this by throwing away the $watches in general. After reading this excellent article: http://www.benlesh.com/2013/10/title.html I dediced to move all to ng-change directives and execute when necessary. The $watches introduced a non-testable magic that was the origin of my problem, it was just not readable anymore.