Magic-Mouse
Magic-Mouse

Reputation: 613

Stop angular from javascript in button using confirm

I have a button:

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

I also have an angular function:

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

When i click cancel in the confirm the console outputs:

1

When i click ok in the confirm the console outputs:

1

I want the angular code to execute when the "Ok" is pressed but not when the "Cancel" is pressed.

JSFiddle example: http://jsfiddle.net/4304ewu5/

Upvotes: 0

Views: 71

Answers (2)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

Throw your confirm inside the $scope.deleteCompany() function:

function MyCtrl($scope) {
  $scope.deleteCompany = function(id) {
    if (confirm('This will permernently delete the entity\nAre you sure you want to delete this post?')) {
      $scope.name = id;
      // delete the stuff.
    }
  }
}

And remove it from the inline HTML:

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

Fiddle: http://jsfiddle.net/0Laztrfk/

Upvotes: 5

Gian Marco Toso
Gian Marco Toso

Reputation: 12136

Why don't you put the confirm within your deleteCompany method?

$scope.deleteCompany = function(id) { 
    if (!confirm("Delete company?"))  
        return;

    console.log(id);
}

Upvotes: 3

Related Questions