is it possible to write an interceptor for ng-click? I have a button or a link that leads to a deletion of an object in the backend. I'd like to have a confirmation dialog (modal) by just adding an attribute to the button/link. E.g.:
<a href="#" ng-click="deleteIt(id)" confirmation-needed>Delete</a>
Is this possible with AngularJS? Is there a better approach do solve this issue?
EDIT The deleteIt method resides in different controllers.
Thx
The ng-click directive tells AngularJS what to do when an HTML element is clicked.
For a single btn, it's ok to use ng-click or onclick in the ng-app . There is no difference between the two functions. For effective team work, you,d better to have an account with each other. In Angular apps, ng-click is recommended.
Another significant difference between ng-click and onclick is the execution context. Code inside an onclick attribute executes against the global window object, while an expression inside of ng-click executes against a specific scope object, typically the scope object representing the model for the current controller.
I've put an example directive in:
http://plnkr.co/edit/GJwK7ldGa9LY90bMuOfl?p=preview
I achieve it by creating a directive:
priority
than ngClick
, so that it gets called before ngClick
,terminal
so that it doesn't call ngClick
.ngClick
value if the message is ok.As a bonus, you can pass in your own message, such as:
<a href="#" ng-click="deleteIt(id)" confirmation-needed="Really Delete?" >Delete with custom message</a>
The code looks like this:
app.directive('confirmationNeeded', function () { return { priority: 1, terminal: true, link: function (scope, element, attr) { var msg = attr.confirmationNeeded || "Are you sure?"; var clickAction = attr.ngClick; element.bind('click',function () { if ( window.confirm(msg) ) { scope.$eval(clickAction) } }); } }; });
Hope that helps.
I've given up on getting Piran's answer to work as I'd like it to. Instead, I've started just replacing ngClick with my own directive:
.directive('confirmClick', function() { return { restrict: 'A', link: function(scope, elt, attrs) { elt.bind('click', function(e) { var message = attrs.confirmation || "Are you sure you want to do that?"; if (window.confirm(message)) { var action = attrs.confirmClick; if (action) scope.$apply(scope.$eval(action)); } }); }, }; })
This directive doesn't even have its own scope, which simplifies combining it with other directives significantly. It takes everything it needs directly from the attrs
. It's used like so:
<span ng-show="editing" confirm-click="delete()" confirmation="delete confirmation message goes here">some text</span>
The delete()
function must exist somewhere higher up in the $scope
chain. I'm sure this could be improved by taking a closer look at how ng-click
is implemented, but I haven't gotten around to it yet!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With