I'm working on implementing a favorite/unfavorite button right now using the Mean stack. I have the backend properly working and am trying to figure out how to conditionally show the correct button. There is a favorite and unfavorite button that use ng-show based on whether or not a particular post(thing to favorite) has already been favorited by the user. The issue is that Angular does not wait while the database is checking if this user has already favorited this post and thus should display the unfavorite button instead. I've messed around with $q and other async options, but I'm not very confident in my understanding of them. Here is the relevant code:
app.isFavorited = $q.defer();
if(Auth.isLoggedIn()) {
app.isLoggedIn = true;
Auth.getUser().then(function (data) {
postObject.username = data.data.username;
if(data.data.favorites.length == 0) {
app.isFavorited.resolve(false);
app.load = true;
}
for(var i = 0; i < data.data.favorites.length; i++) {
if(id == data.data.favorites[i]) {
app.isFavorited.resolve(true)
app.load = true;
break;
}
if(i == data.data.favorites.length - 1) {
app.isFavorited.resolve(false);
app.load = true;
}
}
});
}
else {
app.isLoggedIn = false;
app.load = true;
}
line 55 executes before those which get the values used in ng-show: