Question

I'm playing around with handling the query string on page load, and noticed something about $watch.

It looks like it takes some time for $watch to register when it is called - and this process is asynchronous.

I'm finding that I have to deal with race conditions as my $watch does not trigger when it should - that is, values that are set after the $watch declaration do not get evaluated by the $watch.

See this example for an illustration of the problem: http://jsbin.com/kapifezi/24/edit

Does anyone have a best practice around using watches to avoid this type of issue?

Was it helpful?

Solution

As it turns out - after investigating further - I didn't fully understand how $watch worked.

http://angular-tips.com/blog/2013/08/watch-how-the-apply-runs-a-digest/ really helped shed some light on the situation.

As it turns out - simply changing a variable that is being watched won't trigger a digest loop by itself.

The reason $timeout worked was because it "safely" makes a call to $digest which causes all $watch expressions to be evaluated - that is, it was the $digest component of the $timeout that caused the $watch to fire and not the wait of 1000 milliseconds.

Lesson learned.

OTHER TIPS

do you mean value updated inside $timeout??? there will be 1000 miliseconds delay before $scope.val is changed to 1 inside $timeout and after that $scope.val gets updated

Not really got what do you mean but in my controller if I need watch for some var im doing this:

$scope.myValue = "value";
$scope.$watch("myValue", function(val) {
    if (val) {
        console.out(val);
    }
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top