34

I'm a fish in AngularJS and I have this scenario.

<form>
    <input type="text">
</form>
<button type="submit">submit</button>

In normal ways AngularJS provides the ng-submit directive to work as an attribute in the form but I need to call it outside.

So, someone has experienced the same problem? If yes, what you did?

1
  • 8
    I try to stay as a human when working in Angular, it can be far more advantageous Commented Feb 10, 2015 at 13:02

10 Answers 10

53

Use HTML5's form attribute, here's a sample:

angular.module('app', [])

.controller('MyCtrl', ['$scope', function($scope) {
  $scope.submitted = false;
  
  $scope.confirm = function() {
    $scope.submitted = true;
  };
}]);
form {
  padding:5px;
  border: 1px solid black
}
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body ng-controller="MyCtrl">
  
  <form id="myform" ng-submit="confirm()">
    <label for="myinput">My Input</label>
    <input type="text" id="myinput" name="myinput">
  </form>
  <br>
  
  <input type="submit" value="Submit" form="myform">
  
  <p ng-show="submitted">
    The form was submitted
  </p>

</body>
</html>

Sign up to request clarification or add additional context in comments.

5 Comments

This solution does not appear to be supported by Internet Explorer caniuse.com/#feat=form-attribute
Simplest fix. At first I didn't notice the form= value needs to match the id of the form, not the name of the form (in case it helps someone else). It can also be written as, <button type="submit" form="myform">Save</button>
By far the cleanest solution
This might be a clean solution, but this totally breaks internet explorer support @CorySchires is 100% right on this. I advise everyone who requires IE support to ignore this solution.
It is best to use native solutions like this one. If IE does not support this feature, you should decide not to support legacy browsers like these.
17

Please, surround your code with a ng-controller, and use ng-click on buttons out of scope of <form>.

I make a sample on jsfiddle for you... try it:

http://jsfiddle.net/xKkvj/2/

<div ng-app>
    <div ng-controller="Ctrl">
        <form ng-submit="submit()">Enter text and hit enter:
            <input type="text" ng-model="text" name="text" />
            <input type="submit" id="submit" value="Submit" /> <pre>list={{list}}</pre>
        </form>
        <button ng-click="submit()">Submit 2</button>
    </div>
</div>

with js:

function Ctrl($scope) {
    $scope.list = [];
    $scope.text = 'hello';
    $scope.submit = function () {
        if ($scope.text) {
            $scope.list.push($scope.text);
            $scope.text = '';
        }
    };
}

8 Comments

What if I need to pass the form for validation purposes?: <form name="myForm" ng-submit="submit(myform)">
@benoror, I would to use an object to store input values (ex: $scope.data = {}), and use this on input (ng-model="data.text") and then, I would to pass this object on submit function: submit(data)
actually it's not necessary to put <button> out of <form>, attr type="button" just can be used in order for <button> not to submit the form
@MayurBaldha There are a small error at your code. the ng-submit only run on forms, on buttons you need to use ng-click: button ng-click="submit(form1)"... take a look at: jsfiddle.net/joaozitopolo/xKkvj/446
Form validation won't be triggered using this technique which kind of defeats the point of using a form in the first place...
|
9

This is by far the cleanest solution I found, all credits go to @Offereins https://stackoverflow.com/a/23456905/3819736

<form ng-submit="vm.submit()">
    <input type="text" name="name" />
    <input type="submit" id="submit-form" class="hidden" />
</form>
<label for="submit-form">
    <button type="submit">submit</button>
</label>

This method doesn't require any additional controller JS or other jQuery tweaks.

1 Comment

@TVH7 That link shows only the form= attribute, as answered in stackoverflow.com/a/28432268/3150057, which definitely doesn't work in IE/Edge. This answer, however, is about the for= attribute, which is very common in html =)
5

Angular 2

For anyone looking to achieve the same with Angular 2, ngForm exposes an event emitter you can use.

https://angular.io/api/forms/NgForm

<form role="form" (ngSubmit)="onSubmit()" #myForm="ngForm">
<div class="form-group">
    <label for="name">Name</label>
    <input autofocus type="text" ngControl="name" #name="ngForm" class="form-control" id="name" placeholder="Name">
    <div [hidden]="name.valid || name.pristine" class="alert alert-danger">
        Name is required
    </div>
</div>
</form>
<button type="submit" class="btn btn-primary" (click)="myForm.ngSubmit.emit()">Add</button>

You can also perform the same emit from inside your component ts/js file

1 Comment

This resolved my issue with submitting forms in IE 11 using angular 5. It looks like the above link is dead and is now here: angular.io/api/forms/NgForm
2

All great answers, but the uber-solution, with all your options laid out: http://plnkr.co/edit/VWH1gVXjP2W9T9esnVZP?p=preview

  <form ng-submit="submit()" name="jForm" id="jForm" onsubmit="event.returnValue = false; return false;">
    <input type="text" class="form-control" placeholder="try to hit the enter key in here" />
    <div class="btn btn-default" id="tap">
      Tap me
    </div>

    <div ui-submit="" class="btn btn-primary">Submit form</div>
  </form>
  <ui-submitform class="btn btn-primary" formsubmitfunction="submit()">Submit form 2</ui-submitform>
  <button onclick="$('#jForm').submit()">jquery Submit</button>

and extending @m-k's and combing ideas from @joaozito-polo:

app.directive('uiSubmitform', function()
{
    // need this to make sure that you can submit your form by simply pressing the enter key in one of the input fields
    return {
     restrict: 'E',
     link: function(scope, element, attrs)
     {
        element.onTrigger(function()
        {
          //scope.$apply(attrs.formsubmitfunction); 
            scope.$eval(attrs.formsubmitfunction);
        });
     }
 };
});

Comments

1

Here is my test code. The controller who has the login method is already called!

<form ng-submit="login()" id="form-test" name="formTest">
    <input type="text" name="username">
    <br>
    <input type="password" name="userpass">
    <br>

    <!-- works -->
    <input type="submit" value="submit inside" id="test">
</form>

<!-- change the path from /#/login to /?username=aaa&userpass=aaa#/login and reloads the page-->
<button type="submit" onclick="$('#form-test').submit();">submit outside (jquery)</button> 

<!-- doesn't work -->
<button type="submit" ng-click="formTest.submit()">submit outside (ng-click)</button> 

Comments

1

Short answer Look at http://jsfiddle.net/84bodm5p/


Easiest way for me create special directive for external submission.

Important only use right event .triggerHandler('submit') on form element

$scope.$on('makeSubmit', function(event, data){
              if(data.formName === $attr.name) {
                $timeout(function() {
                  $el.triggerHandler('submit'); //<<< This is Important

                  //equivalent with native event
                  //$el[0].dispatchEvent(new Event('submit')) 
                }, 0, false);   
              }
            })

Look at my answer here How to trigger form submit programmatically in AngularJS?

Comments

1

If you are looking a handle of submitted state of form: In function ng-click just add vm.formName.$setSubmitted();

ng-click="vm.formName.$setSubmitted(); vm.submit()"

Comments

0

There is a solution that works for me:

http://jsbin.com/ODaFaGU/3/edit

Check out the PART 2 and PART 3.

There are two solutions inside.

One for the regular form submit buttons - it allows you to tap the buttons without a delay, but also ensures that pressing the "enter" key in any of the form fields will trigger a submit.

Secondly there is an additional eventHandler that combines the click, tap and keydown[enter] events into a single one - this ensures that you can hit your controls as well with the keyboard, as with a click on desktop, and a tap on mobile(without hitting the click event twice) devices.

If you have any problems with this, give me a comment, I'll fix it.

1 Comment

Hi, it seems confusion for me because i am new to angular so i am sharing my fiddle like which can't be working in IE browser jsfiddle.net/premraj10/LADWU/2 main issue is after edit the row unable click the save event on IE browsers. please have a look it and let me know your solution.
-3

In Angular you don't submit forms (well, at least in the angular way). You just need a function that will do what you want to do when you complete the form.

Just call that function in your <button> and you're ready to go.

Example: plunker

1 Comment

This example isn't helpful if you're looking to take advantage of angular validation. Angular validation is listening specifically for the submit event to run.

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.