In an Angular app, form is validated via custom JS function before submitting. Based on a condition, I need to show a confirmation dialog to the user, wait for confirmation or rejection, then proceed with validation. I'm having difficulties with achieving this asynchronously. I believe I am not using the promise correctly, but not sure what needs to be updated.
Factory
app.factory("confirmDialogService", ['$q', 'ngDialog',
function ($q, ngDialog ) {
return {
popConfirm: function () {
var deferred = $q.defer();
var confirmed;
setTimeout(function () {
ngDialog.openConfirm({
template: 'template/confirmDialog.html',
className: 'ngdialog-theme-default'
}).then(function (value) {
console.log('Modal promise resolved. Value: ', value);
deferred.resolve(confirmed = true);
}, function (reason) {
console.log('Modal promise rejected. Reason: ', reason);
deferred.reject(confirmed = false);
});
}, 1000);
return deferred.promise;
}
};
}]);
Controller
$scope.checkSomething = function (){
if(needsConfirmation)
{
console.log('about to pop confirm');
confirmationService.popConfirm().then(function(confirmed){
console.log( 'from popConfirm() ' + confirmed + ''); // never logged
return confirmed;
}, function(){
// something went wrong
return false;
});
}
else
return true;
}
The confirmation dialog is shown, but clicking yes or no in the dialog does not produce results as expected.
What I'd like to be able to do is get a true/false value depending whether a user confirmed or dismissed the dialog, along the lines of
var canProceed = $scope.checkSomething();
I think I need to wrap this into another promise but not sure how. Any help will be greatly appreciated.
Thanks,
Since
openConfirm
already returns a Promise, you don't need to create one more with$q.defer()
:After that
checkSomething
would use it this way:Note how it no longer returns
true
orfalse
, but rather a promise object. Finally you should use$scope.checkSomething()
like asynchronous operation with promises:Summarizing, the most important thing to understand it that
checkSomething
should return a promise and not just true/false.