I am trying to setup a confirmation dialog on an ng-click
using a custom angularjs directive:
app.directive('ngConfirmClick', [
function(){
return {
priority: 1,
terminal: true,
link: function (scope, element, attr) {
var msg = attr.ngConfirmClick || "Are you sure?";
var clickAction = attr.ngClick;
element.bind('click',function (event) {
if ( window.confirm(msg) ) {
scope.$eval(clickAction)
}
});
}
};
}])
This works great but unfortunately, expressions inside the tag using my directive are not evaluated:
<button ng-click="sayHi()" ng-confirm-click="Would you like to say hi?">Say hi to {{ name }}</button>
(name is not evaluated is this case). It seems to be due to the terminal parameter of my directive. Do you have any ideas of workaround?
To test my code: http://plnkr.co/edit/EHmRpfwsgSfEFVMgRLgj?p=preview
I created a module for this very thing that relies on the Angular-UI $modal service.
https://github.com/Schlogen/angular-confirm
Here is a clean and simple solution using angular promises
$q
,$window
and native.confirm()
modal:Here I'm using
controllerAs
syntax and ES6 arrow functions but it's also working in plain ol' ES5.A clean directive approach.
Update: Old Answer (2014)
It basically intercepts the
ng-click
event, displays the message contained in theng-confirm-click="message"
directive and asks the user to confirm. If confirm is clicked the normalng-click
executes, if not the script terminates andng-click
is not run.Code credit to Zach Snow: http://zachsnow.com/#!/blog/2013/confirming-ng-click/
Update: New Answer (2016)
1) Changed prefix from 'ng' to 'mw' as the former ('ng') is reserved for native angular directives.
2) Modified directive to pass a function and message instead of intercepting ng-click event.
3) Added default "Are you sure?" message in the case that a custom message is not provided to mw-confirm-click-message="".
If you use ui-router, the cancel or accept button replace the url. To prevent this you can return false in each case of the conditional sentence like this: