I am trying to setup a watch on the return value of an asynchronous function, but keep running into infinite digest loops. Here's my $watch
$scope.$watch(function(){
var friendsCount = PublicUserData().then(function(data){
console.log(data.length);
return data.length;
});
return friendsCount;
}, function(newValue, oldValue) {
console.log("change"+ newValue);
});
I can see in the chrome console that both console.log
get called, but the second (on the callback) gets called far more often than the first.
PublicUserData
uses $q
:
.factory('PublicUserData', function($http, $q){
return function(){
var defer = $q.defer();
$http.get('/api/v1/users/').then(function(data){
defer.resolve(data.data.users);
})
return defer.promise;
}
})
I've tried a few things, like setting the watch expression as a $scope outside of my $watch
, but that ends up returning the factory's code, rather than the factory's return value.
Is it possible to use $watch
with a function that implements a promise? Or should I be using something else?