在angularjs中确认对话框

时间:2016-02-19 09:05:12

标签: javascript angularjs confirm-dialog

如何在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;
      }
    };

4 个答案:

答案 0 :(得分:19)

这是片段,

你的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 :(得分:8)

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

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

答案 2 :(得分:3)

我会将消息位与删除操作位分开,这样您就可以在应用的其他部分重用确认位: 我使用像这样的指令:

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-click:

<span><a class="button" ng-confirm-click="Are you sure?" ng-click="removeUser(item.id}}">Delete</span>
希望它有所帮助。

答案 3 :(得分: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)
                    }
                });
            }
        };
}])