Create a confirmation alert for delete button in Angular using JS

妖精的绣舞 提交于 2019-12-02 20:37:24

Seems like an AngularJS directive is a bit over-the-top for a solution to this. Seems easier just to use straight javascript unless you need some custom functionality to your "confirm()" function.

if (confirm('Are you sure you want to delete this?')) {
     // TODO:  Do something here if the answer is "Ok".
}

Hope this helps, cheers

UPDATE: Actually, with Angular, it would be better to use $window.confirm as this would allow you to test with Karma/Jasmine.

Here's another approach at this. Basically it's a directive that gets the warning string you want to show, and the function to call if the user accepts. Usage example:

<button type="button" ng-really-message="Are you sure?"
ng-really-click="delete()">Delete</button>
Christopher Marshall

This is how we're handling our 'confirmation dialogs' (using bootstrap)

The Markup

<div class="alert alert-block alert-error notification fade in" data-ng-show="displayLocationDeletePopup">
    <h6>Are you sure you want to delete this location?</h6>
    <div class="form-controls-alert">
        <a href="" class="btn" data-ng-click="showDeleteLocationPopup(false)">No</a>
        <a href="" class="btn btn-danger" data-ng-click="deleteVendorLocation(locationId)">Yes</a>
    </div>
</div><!-- end alert -->    

Setting model to false on controller load to hide by default with ng-show

$scope.displayLocationDeletePopup = false;

On click on event for show popup, calls a function/passes model in

<i class="icon-remove" data-ng-click="showDeleteLocationPopup(true, location)"></i>

In the controller:

$scope.showDeleteLocationPopup = function(options, id) {
    if (options === true) {
        $scope.displayLocationDeletePopup = true;
    } else {
        $scope.displayLocationDeletePopup = false;
    }
    $scope.locationId = id;
};

And per the anchors in the html above, can either close the popup or run the function

$scope.deleteVendorLocation = function (storeLocation) {
   // Code to run on confirmation            
};
Av.Raj
var r = confirm("Are you sure you want to Permanently delete this order?");
if (r == true) {
    (OK button click) Write the function here.....
} else {
    (Cancle button click) Write the function here.....
}

Place Delete option on the right hand side of each record and on clicking the delete option the record should get deleted from the details and JSON array.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!