10

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?

1 Answer 1

24

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>
Sign up to request clarification or add additional context in comments.

3 Comments

This is correct. "A button element with no type attribute specified represents the same thing as a button element with its type attribute set to "submit""
Oh dear, how embarrassing! I was blindly assuming that the issue was with Angular. Thanks for pointing that out!
Link to @Tom's reference to html spec w3.org/TR/html-markup/button.html.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.