AngularJS Prompt Box Confirmation

Is there a way to implement a confirmation dialog box for the delete button in angularjs?

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

Here's an example of how you can achieve this.

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

Update

This is my current approach:

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

Answer №1

Below are the code snippets provided:

Here is how your HTML code should look like:

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

Make sure to add this directive in your custom angularjs file:

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

Modify your angular scope accordingly based on the delete function mentioned above:

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

Answer №2

$scope.deleteUser = function (index) {
 if (confirm("Are you sure you want to delete this user?")) {
    alert("User deleted successfully");
    $window.location.href = 'delete/' + index;
 }
}

Link to JSFiddle for deleteUser function

Answer №3

To enhance the functionality of your app, consider separating the message component from the delete action component. By doing so, you can easily reuse the confirm feature in various sections of your application. I implement this using a directive as shown below:

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

Next, define your controller function that contains the delete action:

$scope.removeUser(index) {
  //perform necessary actions
}

In the View section, utilize ng-click as follows:

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

I hope this explanation proves beneficial for your project.

Answer №4

Check out this plunker for a solution: http://plnkr.co/edit/xJJFxjYeeHmDixAYPu4c?p=preview Implementing a directive for the dialog functionality is recommended.

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

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

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

app.directive('ngConfirmClick', [
   function(){
       return {
           link: function (scope, element, attr) {
               var message = attr.ngConfirmClick || "Are you sure?";
               var action = attr.confirmedClick;
               element.bind('click',function (event) {
                   if ( window.confirm(message) ) {
                       scope.$eval(action)
                   }
               });
           }
       };
}])

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Interacting div elements with jQuery's dynamic content

I am searching for a way to populate a div with content based on my click selection. To begin, I create a dynamic table like the one below: user name total hours worked button(unique id fetched from database) user name total ho ...

Tips for fixing connection issues when trying to connect to MongoDB on AWS Cloud9

I've been following a tutorial from 'Web Dev Simplified' using the AWS-Cloud9 Ubuntu environment and everything was going smoothly until I encountered an issue while trying to connect to MongoDB. The database appeared to install correctly us ...

Troubleshooting Multer to fix image payload issues in a Node.js and React.js application

Currently, I am facing an issue while trying to send an image from my ReactJS frontend to my NodeJS Express backend using formData. Despite seemingly correct data transmission, the image does not appear in the payload and triggers this error from the backe ...

how to modify attributes of the :before pseudo-element using jQuery

Can you explain how to modify the property of the :before element? For instance: Using CSS: .myclass:before { content: ''; position: absolute; left: 40px; top: ...

What is the process for fetching the chosen outcome from a subsequent webpage using HTML?

How can I display selected cities on a different webpage after clicking a button? Currently, I can only get the results on the same page. For example, if a user selects NYC and Delhi, those cities should be displayed on another HTML page. ...

Troubleshooting an AngularJS and Express routing problem

While working with AngularJS and ExpressJS, I encountered an issue with routing. Despite looking at several other solutions online, none of them seemed to solve my problem. Below are the routes defined in Express: module.exports = function(app, auth) { ...

Is there a way for me to choose a single file while executing the migrate-mongo up command?

Hey there! I'm looking to execute the command migrate-mongo up in just one specific file. Currently, when I run the command migrate-mongo up, it processes all pending migration files. Is there a way to target only one file for execution? For example: ...

Tips for fetching data from a database using AJAX when the values of two drop-down lists are involved

I have successfully implemented an Example where I retrieve data using a single drop-down list from a database. Now, I want to extend this functionality to work with two drop-down lists, where the values retrieved from the database are dependent on the sel ...

Tampermonkey only allows jQuery Click to execute once within a for loop

Attempting to switch the content of a text area to different cars and then trigger a button click to perform an action, repeating this process for each car until all cars have been processed. var index; var cars = ["car1", "car2", "car3"]; var x = documen ...

Acquiring data from an API response in JSON format using JavaScript

Utilizing a parse.com API server, I have successfully established communication in JavaScript through AJAX. The output from the response is being logged into the browser console with the following code: $.ajax(settings).done(function(response) { ...

VueJS / v-html is displaying a blank page (Bokeh-html)

Especially as a newcomer to VueJS, I am currently in the process of trying to showcase a local HTML file within the Vue Application. The method I'm using to fetch the HTML file involves Axios, here's how it goes: <template> <div> ...

What is the best way to bind the value of total when working with forms and the bind method?

I am working on a form where I need to pass the value of total. Regarding the total: I have successfully passed the value of the cart, which is an array. const [total, setTotal] = useState<number | undefined>(undefined); const calculateTotal = () ...

Just starting out with AngularJS, running into a problem with ngResource

As a newcomer to AngularJS, I am attempting to create my first app using the reed.co.uk API. Please bear with me as I navigate through this process! :) Currently, my application is very basic and includes the following: index.html <!DOCTYPE html> ...

Accessing the text content of the clicked element using vanilla JavaScript

Retrieve an item from the dropdown list and insert it into a button's value. function updateButton() { document.getElementById("ul").classList.toggle("show"); } var dropdown = document.getElementById('ul'); var items = ["HTML", "CSS", "Ja ...

Performing a bulk create operation with Sequelize using an array

I am facing a task where I have an array of items that need to be created in the database. My approach is to check each insertion for success. If successful, I will add the item with a flag indicating success as true in a new array (results) in JSON forma ...

Tips for adding a gradient to your design instead of a plain solid color

I stumbled upon a snippet on CSS Tricks Attempting to replace the green color with a gradient value, but unfortunately, the value is not being applied. I have tried using both the fill property and gradient color, but neither has been successful. Here is ...

Conceal the navbar during the process of the ajax loader loading

My current issue involves utilizing an AJAX loader to conceal my page until all elements have loaded. Unfortunately, the navbar is not hidden along with the other content as shown in the image below. I need assistance in ensuring that everything, including ...

Developing tabbed sections in XSLT

Utilizing Angular JS within XSLT, I am aiming to develop a tab-based user interface using XML data. The requirement is to generate multiple links and corresponding div elements based on the number of nodes in the XML. To manage the display of these div ele ...

Discovering if a value has been entered into an input field in AngularJS can be achieved by verifying its availability

Is there a way to check if the value entered in an input field is already in a specified array? I would like to validate the input field value on key press against an array of names and display an error message if the value is already present in the array. ...

Dependency management in ReactJS components

I am grappling with the optimal structure for a React component that is composed of other components. Let's look at the first example: <ColorSelect id="color" label={this.state.selectLabel} trigger={{ color: "lime", text: "Lime"}} onPropagateCli ...