Vivek Jha Vivek Jha - 4 months ago 19
AngularJS Question

Retrofitting "alert()" on delete buttons

I have an angular application which contains several delete buttons somewhat like this:

<button class="btn btn-default" ng-click="delete($index)">x</button>

Now as we are nearing production deployment and I want delete buttons to behave nicely and "alert()" the user before actually deleting the object.

How can I retro-fit this feature in all the delete buttons through a directive. I would like to have a directive called "ask":

<button ask class="btn btn-default btn-xs" ng-click="delete($index)">x</button>

which I can use to affect the behaviour of any button.

Somehow I am not able to think through this

app.directive("ask", function() {
return function(scope, elems, attrs) {
// what to do here:
// 1. shall I change the elems.attr("ng-click")
// 2. or scope.attrs("ngClick")

Please guide me with the best practice and some code samples. Also note that the ng-click callback of all the delete buttons are different and the application already makes extensive use of isolate scope and child scope directives.


Try this implementation

  .module('test', [])
  .directive('ask', function() {
    return {
      restrict: 'A',
      scope: {ask: '@', onAsk: '&'},
      link: function(scope, elem, attrs) {
        elem.on('click', function(e) {
          if(confirm(attrs.ask)) {
  .controller('ItemsCtrl', function($scope) {
    $scope.items = [1,2,3,4,5];
    $scope["delete"] = function(index) {
      $scope.items.splice(index, 1);
<script src=""></script>
<div ng-app="test" ng-controller="ItemsCtrl">
  <ul><li ng-repeat="item in items track by $index">{{item}}
  <button ask="Are you sure you want to delete item?" on-ask="delete($index)">x</button>