Search code examples
javascriptangularjseventspreventdefault

How can i prevent default in confirm dialog in Angular JS


I have this in my save function

$scope.saveData = function () {

   if (confirm("Are you sure you want to save") === false) {
       return
    }


// do saving

Now if i use above code then i get this after clicking yes. Even if i click cancel i still get same error in firebug. But my data get saved if i click yes but error is still there. I only see this in firefox and not in chrome.

If i remove confirm dialog then that error is gone. so its definitely related to dialog

Error: [$rootScope:inprog] $apply already in progress http://errors.angularjs.org/1.2.25/$rootScope/inprog?p0=%24apply

SO i was thinking may be i need to

e.preventDefault();

How can i use that in above function. I am using like this

ng-click = "saveData()"


Solution

  • <button ng-click="saveData($event)">Save</button>
    

    Firefox doesn't auto pass in the event for some reason, so you have to pass it from the markup.

    $scope.saveData = function (e) {
    
       if (confirm("Are you sure you want to save") === false) {
           e.preventDefault();
           return;
        }
        // do saving
    };