Reputation: 2047
I read articles about $digest cycle and $scope.$apply() as many as possible, but couldn't get to the point how to change my data on the callback.
This is my method:
vm.showAllResults = showAllResults;
function showAllResults(){
// Prevent 'bubbling'
event.preventDefault();
event.stopPropagation();
// Second parameter notifies search to show full list of elements
vm.search(vm.input.query, true);
$scope.$apply(function(){
vm.showAll = false;
});
}
vm.search(vm.input.query, true) - is doing some async work with vm.showAll too. Afterwards I want to set it as false.
But I can't get inside of $scope.$apply(). What am I doing wrong? Thanks!
Upvotes: 1
Views: 80
Reputation: 503
To answer your question directly: I'm strongly suspect that you're getting the console.error:
$apply already in progress
which causes the $apply callback to not run.
That said, you can get around that by using $timeout( cb ) instead of $scope.$apply( cb ). Be sure to dependency inject it if you want to use it:
vm.showAllResults = showAllResults;
function showAllResults(){
// Prevent 'bubbling'
event.preventDefault();
event.stopPropagation();
// Second parameter notifies search to show full list of elements
vm.search(vm.input.query, true);
$timeout(function(){
vm.showAll = false;
});
}
However, as Avraam pointed out, in my opinion as well, vm.search should be a deferred method using $q (also dependency injected) which returns a promise, and calls .resolve/reject, which you use with .then like this:
vm.showAllResults = showAllResults;
function showAllResults(){
// Prevent 'bubbling'
event.preventDefault();
event.stopPropagation();
// Second parameter notifies search to show full list of elements
vm.search(vm.input.query, true)
.then( function() {
$timeout( function() { // <-- This $timeout probably not needed...
vm.showAll = false;
});
});
}
Upvotes: 2