I'm having a problem with a callback that I'm trying to implement, hope you can help me.
Here is my html:
<a class="btn btn-primary btn-xs address-pager" ng-disabled="citizensCtrl.addressIndex==citizensCtrl.citizen.addresses.length-1" ng-click="citizensCtrl.nextAddress()">
<span class="glyphicon glyphicon-chevron-right"></span>
</a>
The function in ng-click is:
self.nextAddressIndexCallBack = function(){
console.log('d');
self.addressIndex = self.addressIndex+1;
};
self.nextAddress = function(){
if(self.citizen.addresses[self.addressIndex].district){
self.getAddresses(false);
self.getZipCodes(self.nextAddressIndexCallBack());
}
};
In the function getZipCodes is where I found my problem:
self.getZipCodes = function(callback){
if(self.citizen.addresses[self.addressIndex].public_place.id){
$http.get(apiUrl + "/addresses/" + self.citizen.addresses[self.addressIndex].public_place.id + "/zip_codes").then(function(response){
console.log('a');
self.zip_codes[self.addressIndex] = response.data;
console.log('b');
if(callback){
callback;
}
});
}
};
So, the correct runtime that I expected was console (a,b,d). But this is consoling(d,a,b).
This is the best way to implement a callback? And how I do it be synchronous and execute only when it is called on getZipCodes function?
self.nextAddressIndexCallBack() causes the execution to the function, and the result of that to be passed to the calling function..
Can you try the following changes:
self.nextAddress = function(){
if(self.citizen.addresses[self.addressIndex].district){
self.getAddresses(false);
//self.getZipCodes(self.nextAddressIndexCallBack());
self.getZipCodes(self.nextAddressIndexCallBack);
}
};
self.getZipCodes = function(callback){
if(self.citizen.addresses[self.addressIndex].public_place.id){
$http.get(apiUrl + "/addresses/" + self.citizen.addresses[self.addressIndex].public_place.id + "/zip_codes").then(function(response){
console.log('a');
self.zip_codes[self.addressIndex] = response.data;
console.log('b');
if(callback){
//callback();
callback();
}
});
}
};