I am trying to setup a confirmation dialog on an ng-click
using a custom angularjs directive:
app.directive(\'ngConfirmClick\', [
function()
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:
app.directive('confirmationNeeded', function () {
return {
link: function (scope, element, attr) {
var msg = attr.confirmationNeeded || "Are you sure?";
var clickAction = attr.confirmedClick;
element.bind('click',function (event) {
if ( window.confirm(msg) )
scope.$eval(clickAction);
return false;
});
}
}; });
An angular-only solution that works alongside ng-click
is possible by using compile to wrap the ng-click
expression.
Directive:
.directive('confirmClick', function ($window) {
var i = 0;
return {
restrict: 'A',
priority: 1,
compile: function (tElem, tAttrs) {
var fn = '$$confirmClick' + i++,
_ngClick = tAttrs.ngClick;
tAttrs.ngClick = fn + '($event)';
return function (scope, elem, attrs) {
var confirmMsg = attrs.confirmClick || 'Are you sure?';
scope[fn] = function (event) {
if($window.confirm(confirmMsg)) {
scope.$eval(_ngClick, {$event: event});
}
};
};
}
};
});
HTML:
<a ng-click="doSomething()" confirm-click="Are you sure you wish to proceed?"></a>
You can use id with a message or without. Without message the default message will show.
Directive
app.directive('ngConfirmMessage', [function () {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.on('click', function (e) {
var message = attrs.ngConfirmMessage || "Are you sure ?";
if (!confirm(message)) {
e.stopImmediatePropagation();
}
});
}
}
}]);
Controller
$scope.sayHello = function(){
alert("hello")
}
HTML
With a message
<span ng-click="sayHello()" ng-confirm-message="Do you want to say Hello ?" >Say Hello!</span>
Without a messsage
<span ng-click="sayHello()" ng-confirm-message>Say Hello!</span>
Its so simple using core javascript + angular js:
$scope.delete = function(id)
{
if (confirm("Are you sure?"))
{
//do your process of delete using angular js.
}
}
If you click OK, then delete operation will take, otherwise not. * id is the parameter, record that you want to delete.
I created a module for this very thing that relies on the Angular-UI $modal service.
https://github.com/Schlogen/angular-confirm