Intercepting ng-click in angularJS

前端 未结 4 1327
一生所求
一生所求 2020-12-05 05:17

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

4条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 05:55

    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:

    some text
    

    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!

提交回复
热议问题