george george - 5 months ago 126
AngularJS Question

angularjs: confirmation dialog not working properly

i am trying to create a confirmation dialog in angularjs, i found an answered question about that in stackoverflow
Confirmation dialog on ng-click - AngularJS
i tried it as it is answered but when i click cancel it works as if i clicked OK is the answer wrong or should i add something else

<button type="button" ng-click="updateData()" ng-confirm-click="Are you sure?">
Update
</button>


directive

app.directive('ngConfirmClick', [
function(){
return {
link: function (scope, element, attr) {
var msg = attr.ngConfirmClick || "Are you sure?";
var clickAction = attr.confirmedClick;
element.bind('click',function (event) {
if ( window.confirm(msg) ) {
scope.$eval(clickAction)
}
});
}
};
}])

Answer

I had the same problem, and I solved using your same directive, but, instead of using ng-click for the final action on user confirmation, I did use the attribute confirmed-click with the final action as it's value.

html:

<button confirmed-click="confirm()" ng-confirm-click="Are you really sure?">Update</button>

directive:

app.directive('ngConfirmClick', [
    function() {
        return {
            link: function (scope, element, attr) {
                var msg = attr.ngConfirmClick || "Are you sure?";
                var clickAction = attr.confirmedClick;
                element.bind('click',function (event) {
                    if (window.confirm(msg)) {
                        scope.$eval(clickAction)
                    }
                });
            }
        };
    }
]);

See this fiddle.