2016-02-19 105 views
8

如何在angularjs中的以下按钮中应用确认对话框?在angularjs中确认对话框

<button class="btn btn-sm btn-danger" ng-click="removeUser($index)">Delete</button> 

就像这样。

<span><a class="button" onclick="return confirm('Are you sure to delete this record ?')" href="delete/{{ item.id }}">Delete</span> 

更新

目前,我做这样的

function removeUser(index) { 
     var isConfirmed = confirm("Are you sure to delete this record ?"); 
     if(isConfirmed){ 
     vm.users.splice(index, 1); 
     }else{ 
     return false; 
     } 
    }; 

回答

13

这里是片段,

如何你的HTML应该是,

<button class="btn btn-sm btn-danger" ng-confirm-click="Are you sure to delete this record ?" confirmed-click="removeUser($index)">Delete</button> 

请包括这个指令在自定义angularjs文件,

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) 
        } 
       }); 
      } 
     }; 
}]) 

你的角范围基础在你上面提到的删除功能上,

$scope.removeUser = function(index) { 
    vm.users.splice(index, 1); 
} 
+1

工作完美!谢谢。 –

5
$scope.removeUser= function (ind){ 
if (confirm("Are you sure?")) { 
    alert("deleted"+ s); 
    $window.location.href = 'delete/'+ s; 
} 
} 

http://jsfiddle.net/ms403Ly8/61/

+0

完美答案!! –

1

我会从删除操作位消息位分开,这样,你可以重新使用其他的确认位您的应用程序的部分: 我用一个指令,像这样:

angular.module('myModule').directive("ngConfirmClick", [ 
    function() { 
    return { 
    priority: -1, 
     restrict: "A", 
     link: function(scope, element, attrs) { 
     element.bind("click", function(e) { 
      var message; 
      message = attrs.ngConfirmClick; 
      if (message && !confirm(message)) { 
      e.stopImmediatePropagation(); 
      e.preventDefault(); 
      } 
     }); 
     } 
    }; 
    } 
]); 

然后让你的控制器功能与删除操作:

$scope.removeUser(index) { 
    //do stuff 
} 

,并在视图我会用NG-点击:

<span><a class="button" ng-confirm-click="Are you sure?" ng-click="removeUser(item.id}}">Delete</span> 

希望它有帮助。

0

您可以尝试下面这个plunker:http://plnkr.co/edit/xJJFxjYeeHmDixAYPu4c?p=preview 您可以创建对话框的指令。

var app = angular.module('plunker', []); 

app.controller('MainCtrl', function($scope, $window) { 

    $scope.delete = function(id) { 
    $window.location.href = 'delete/'+ id; 
    } 
}); 

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) 
        } 
       }); 
      } 
     }; 
}])