1
<div ng-app>
  <div ng-controller="Ctrl">
     <form ng-submit="submit() ">
       <textarea ng-model="text" required></textarea>

       <div  ng-click="submit()" style="background-color:#ff00ff;cursor:pointer;width:100px;">Create !</div>

       <button type="submit" style="background-color:#ff00ff;cursor:pointer;width:100px;">Create !</button>

    </form>
    {{list}}
  </div>
</div>

I want to submit an Angular form with a custom div button but when I do it like above, the "required" statements are not taken into account like it is done for the button.

When the textarea is empty the first button runs the submit() function anyway. Is it possible to have the same behavior as the button ?

Here is a JsFiddle illustrating this: http://jsfiddle.net/xKkvj/55/

Hssen
  • 188
  • 1
  • 11

2 Answers2

3

I think you should be using an input rather than a div, eg:

<input type="submit" ng-click="submit()" style="background-color:#ff00ff;cursor:pointer;width:100px;">Create !</input>

I've tested it on your jsFiddle, and it works fine.

If you really must use a <div>, use it to wrap the <input>

UPDATE

It looks like you can't use anything other than an input or a button as that is what ngForm listens to for form submission. You could either extend ngForm or you could use a hidden button and trigger that from your div like so:

<div onClick="document.getElementById('hiddenButton').click();" style="background-color:#0000ff;cursor:pointer;width:100px;">Create !</div>
<button id='hiddenButton' type="submit" style="display:none;">Create !</button>

jsFiddle here. Hopefully this'll do the trick for you.

Caspar Harmer
  • 8,097
  • 2
  • 42
  • 39
  • the input with type="submit" behaves like a button. Wrapping it in a div just creates a button in the div. My goal is to use the div as a button – Hssen Sep 14 '14 at 04:14
0

If you want to submit form from a div element, then you should manually test if form is valid in your submit handler:

function sumbit() {
if (form.$invalid) {
return;
}
// Other code...
}

The point is that when you submit your form via <input type="submit"/>, then form validation check is performed internally & form handler do not invoked in case of invalid form.

UPDATE

Your jsfiddle form handler should look like:

$scope.submit = function () {
        if ($scope.submitCreateSurveyForm.$invalid) {
            return;
        }
        if ($scope.text) {
            $scope.list.push($scope.text);
            $scope.text = '';
        }
        console.log("sent");
    };
Alexey
  • 1,257
  • 7
  • 13