Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ng-submit called twice

I have an angular form whose submit method is being hit twice, and I can't figure out why. I'm pretty new to Angular, so it's possible I'm overlooking something fairly simple...

Html:

<div ng-app="RegistrationApp" ng-controller="RegistrationController">
    <form name="accountForm" ng-submit="submitAccount($event, accountForm, account)"  novalidate>

        // inputs here...

        <button type="submit" class="btn btn-success pull-right" ng-disabled="accountForm.$invalid">Submit</button>
    </form>
</div>

Js:

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

RegistrationApp.controller('RegistrationController', function ($scope) {

    $scope.submitAccount = function (evt, form, account) {
        console.log('submitAccount() hit'); 
        console.log(evt);
        console.log(form);

        evt.stopPropagation();

        // AJAX code
    });
});

Console Window:

submitAccount() hit 
o.Event {originalEvent: Event, type: "submit", isDefaultPrevented: function, timeStamp: 1394139847226, jQuery210012237170152366161: true…}
c {$error: Object, $name: "accountForm", $dirty: true, $pristine: false, $valid: true…}

submitAccount() hit 
o.Event {originalEvent: Event, type: "submit", isDefaultPrevented: function, timeStamp: 1394139847226, jQuery210012237170152366161: true…}
Constructor {$error: Object, $name: "accountForm", $dirty: true, $pristine: false, $valid: true…}

So, the first thing I tried was to stop propagating the event, but that doesn't have any real effect. After going through the event objects, they're seem identical. The only thing that differs is the 'form' object. The properties are the same, except that one shows that "c" and the other shows "Constructor".

Any ideas what could be causing this to trigger twice? The event target is set to the form element in both cases, and I'm not using any onclick functions, or any other sorts of events in the form.

like image 888
Logan Black Avatar asked Mar 06 '14 21:03

Logan Black


1 Answers

One reason happend to me, I'm not sure if this will happen to any other :)

In my controller I had:

$scope.submit = function() { someThingHere };

In the view

<form ng-submit="submit()">
</form>

This way that form has been submitted "mysteriously" two times, to solve that I had to rename $scope.submit to something else.

like image 147
Walid Ammar Avatar answered Sep 17 '22 12:09

Walid Ammar