Confirmation dialog on ng-click - AngularJS

poiuytrez picture poiuytrez · Aug 19, 2013 · Viewed 243.9k times · Source

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

Answer

Michael Low picture Michael Low · Aug 19, 2013

If you don't mind not using ng-click, it works OK. You can just rename it to something else and still read the attribute, while avoiding the click handler being triggered twice problem there is at the moment.

http://plnkr.co/edit/YWr6o2?p=preview

I think the problem is terminal instructs other directives not to run. Data-binding with {{ }} is just an alias for the ng-bind directive, which is presumably cancelled by terminal.