Prevent angular from being executed through a JavaScript function triggered by a button click

Here is a button:

<button ng-click="deleteCompany(company.id)" 
  class="btn btn-danger" 
  onClick="return window.confirm('This will permanently delete the entity\n
           Are you sure you want to delete this post?'); ">
   <span class="glyphicon glyphicon-trash"></span>
</button>

Additionally, there is an angular function:

$scope.deleteCompany = function(id){
        console.log(id);
}

After clicking "Cancel" in the confirm dialog, the console displays:

1

And when clicking "Ok," the console shows:

1

The goal is for the angular code to run only when "Ok" is pressed, not when "Cancel" is chosen.

View the JSFiddle demonstration here: http://jsfiddle.net/4304ewu5/

Answer №1

Make sure to place your confirm function inside the $scope.deleteCompany() method:

function MyCtrl($scope) {
  $scope.deleteCompany = function(id) {
    if (confirm('This action is irreversible\nAre you sure you want to proceed?')) {
      $scope.name = id;
      // perform deletion operation.
    }
  }
}

Also, remove it from the inline HTML code:

<div ng-controller="MyCtrl">
  <button ng-click="deleteCompany('1')" class="btn btn-danger">
    <span class="glyphicon glyphicon-trash"></span>
  </button>
  <button ng-click="deleteCompany('2')" class="btn btn-danger">
    <span class="glyphicon glyphicon-trash"></span>
  </button>
  Hello, {{name}}!
</div>

Check out this demo on Fiddle: http://jsfiddle.net/0Laztrfk/

Answer №2

Have you considered incorporating the confirm function into your deleteCompany method?

$scope.deleteCompany = function(id) { 
    if (!confirm("Are you sure you want to delete this company?"))  
        return;

    console.log(id);
}

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

Unable to invoke the Socket.on() function in NodeJS

I have set up a PHP web app and I am trying to integrate nodeJS into it. I followed a tutorial on nodeJS and got it working fine on localhost:3000. But now, I want to run it on a specific URL like localhost/final/chat/chat_index.html. To achieve this, here ...

Creating a delay in a test to ensure a 5-second wait before validating the appearance of an element using React testing library

I am currently facing an issue in my React component where an element is supposed to appear after a delay of 5 seconds. I have been trying to write a test using 'jest fake timers' to check if the element appears after the specified time, but hav ...

Collect all wallet objects and store them in an array of objects within BitGO for Bitcoin

My Setup: Using the Mongoose module to handle all MongoDB operations, we generate and store a wallet inside a Mongo collection for each new user. METHOD: By using User.find({}, function(err, docs) {, we can retrieve each user object. User.find({}, functi ...

Load the content of the dialog and transfer variables

After struggling for days, I am still unable to find a solution to my current dilemma. In my database, there are approximately 1300 items each with its own unique "id", a corresponding "name", and a property called "enabled". My goal is to display links t ...

An effective method to utilize .map and .reduce for object manipulation resulting in a newly modified map

Here's an example of what the object looks like: informations = { addresses: { 0: {phone: 0}, 1: {phone: 1}, 2: {phone: 2}, 3: {phone: 3}, 4: {phone: 4}, 5: {phone: 5}, }, names: { 0 ...

How can the issue of v-slot missing in Vue2.7 be resolved?

After executing the given code, the results displayed are captured in Google Chrome. Below is a snippet of the code used: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-e ...

JavaScript Equivalent of Declaration in TypeScript

In my Next JS application, I encountered a situation where a line of code relies on a variable from a script src in the app.tsx page. Here's how it looks: app.tsx: <script src="https://js.stripe.com/v3/"></script> config.ts: de ...

Ways to transfer a value from ng-Init to the following controller

Upon loading the Index page, a userName is retrieved. Controller Action in MVC public ActionResult Index() { string userName = "Current User" return View((object)userName); } Subsequently, an attempt is made to store this value using ng-init. Ind ...

Django is not equipped to render AngularJS resources

I'm having trouble displaying data from Django Tastypie in my AngularJS application using the $resource service. The issue I'm facing is that on the HTML page, I only see blank spaces instead of the expected list buttons corresponding to the retu ...

Struggling with deploying Next.js on Vercel

Encountered an issue while trying to deploy a project on Vercel. The error message is as follows: fileName: comps/Navbar.js imported as import Navbar from "./Navbar"; 16:36:51 ModuleNotFoundError: Module not found: Error: Can't reso ...

"An issue arises when using req.body and res.render as the values retrieved are

Encountering an unusual problem - when using req.body to transmit form input to another page, the data is properly displayed when a single word is used in the input field (e.g. "FullName"). However, when there is a space, such as in the example "Full Name" ...

What is the method for writing to an HTML file with the use of expressjs?

Alright, I have an interesting idea here. I am looking for a way to allow users to push a button and have a new p element permanently added to the HTML file. This means that even after reloading the page, everyone should be able to see this new element. An ...

Is placing JavaScript on the lowest layer the best approach?

I'm facing a unique situation that I haven't encountered before and am unsure of how to address it. My website has a fixed top header and footer. On the left side, there is a Google Adsense ad in JavaScript. When scrolling down, the top header s ...

Tips for storing the output of a script URL in a JavaScript variable

I am currently facing an issue with running a script in the 'head' element of a webpage. The script makes an API call to a specific URL and retrieves results in the form of a JavaScript array. However, I am encountering difficulty because the API ...

Experience the simplicity of running basic Javascript Scratch code within IntelliJ IDEA Ultimate

Is there a straightforward way to run and debug a basic JavaScript code in IntelliJ Idea Ultimate without the need for additional setup like creating an HTML file or npm project? I'm looking to avoid boilerplate tasks and wondering if there's an ...

Switching the background image dynamically in Vue.js upon page access

My goal is to update the 'background-image' when the page is accessed. export default { created () { document.getElementsByTagName('html')[0].style.background = "url('../assets/background-blur.png') center" } } //Logi ...

Unable to conceal adjacent element when z-index is set as 1

I encountered an issue where a modal is overlapping another element, and the close button of the underlying element has a z-index of 1. Despite creating a new modal with its own close button, the original close button remains visible on top. I attempted t ...

Retrieving a numeric attribute from a JSON structure

Recently, I encountered an issue with a PHP multidimensional array that I converted to JSON using JSON_encode(). Since I am working with Drupal, the arrays often contain keys that look like this: $some_array['und']['0']['value&a ...

Null value arising due to AJAX's asynchronous nature

I am facing an issue with a form that includes a select option displaying various choices. My goal is to retrieve the selected option and display it in a text box. The options are loaded using AJAX from an XML data source. When attempting to grab the sele ...

Managing numerous callbacks for a specific route within Express.js

After going through the Express.js documentation, I came across a section discussing how to handle callbacks for routes using the syntax: app.get(path, callback [, callback ...]) However, I encountered difficulty in finding an example that demonstrates ...