Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AngularJS ng-submit event handler gets called even when not submitting

Tags:

angularjs

I'm trying to set up form validation using angular-ui. I want to check that the form is valid before submitting it, so I have set up a ng-submit event handler.

But before even implementing any validation, I noticed that the event handler gets called even when not submitting the form. In the example below, it gets invoked when I click the Add Item button:

<div ng-app="app">
    <div ng-controller="ctrl">
        <form name="myForm" ng-submit="sub()" novalidate>                    
            <div ng-repeat="item in items">
                <ng-form name="row">
                    <input type="text" name="value" ng-model="item.value" required />                    
                </ng-form>
            </div>         
            <button ng-click="addItem()">Add Item</button>        
            <input type="submit" value="Submit"/>
        </form>
    </div>
</div>  

And JS:

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

 app.controller('ctrl', ['$scope', function($scope) {
     $scope.items = [];
     $scope.addItem = function() {
         $scope.items.push({ value: $scope.items.length });
     };

     $scope.sub = function() {
         alert("submitted?");
     };
  }]);

See my fiddle here:

http://jsfiddle.net/UvLBj/2/

Is this supposed to happen? Seems wrong to me that the ng-submit isn't just fired on form submit... Have I done something wrong?

like image 954
Simon Green Avatar asked Feb 18 '14 19:02

Simon Green


1 Answers

Believe you need to add type="button" to avoid the accidental call to submit. Updated the fiddle and seems to fix it:

http://jsfiddle.net/UvLBj/3/

<button type="button" ng-click="doSomething()">Test</button>
like image 120
shaunhusain Avatar answered Nov 14 '22 04:11

shaunhusain