Html AngularJS:在表单外调用 ng-submit 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18581269/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 12:57:10  来源:igfitidea点击:

AngularJS: Call the ng-submit event outside the form

javascripthtmlangularjsangularjs-directiveform-submit

提问by Cald

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

我是 AngularJS 中的一条鱼,我有这个场景。

<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.

在正常情况下,AngularJS 提供 ng-submit 指令作为表单中的属性,但我需要在外部调用它。

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

那么,有人遇到过同样的问题吗?如果是,你做了什么?

采纳答案by Joao Polo

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

请用 ng-controller 包围您的代码,并在 <form> 范围之外的按钮上使用 ng-click。

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

我为你制作了一个关于 jsfiddle 的示例......试试看:

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

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:

与js:

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

回答by Hodes

Use HTML5's formattribute, here's a sample:

使用 HTML5 的form属性,这里是一个示例:

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>

回答by sbedulin

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

这是迄今为止我找到的最干净的解决方案,所有学分都归于@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.

此方法不需要任何额外的控制器 JS 或其他 jQuery 调整。

回答by edqwerty

Angular 2

角 2

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

对于希望使用 Angular 2 实现相同目标的任何人,ngForm 公开了一个您可以使用的事件发射器。

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

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

您还可以从组件 ts/js 文件中执行相同的发射

回答by Cald

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> 

回答by OzBob

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

所有很好的答案,但超级解决方案,包括所有选项: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:

并扩展@mk 并结合@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);
        });
     }
 };
});

回答by non4me

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

简短的回答看http://jsfiddle.net/84bodm5p/



Easiest way for me create special directive for external submission.

对我来说最简单的方法是为外部提交创建特殊指令。

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

重要的是仅在表单元素上使用正确的事件 .triggerHandler('submit')

$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?

在此处查看我的答案如何在 AngularJS 中以编程方式触发表单提交?

回答by Niklavr

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();

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

回答by M K

There is a solution that works for me:

有一个对我有用的解决方案:

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

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

Check out the PART 2 and PART 3.

查看第 2 部分和第 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.

其次,还有一个额外的 eventHandler 将 click、tap 和 keydown[enter] 事件组合成一个单一的事件 - 这确保您也可以使用键盘点击您的控件,就像在桌面上点击一样,在移动设备上点击(没有点击两次点击事件)设备。

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

如果您对此有任何问题,请给我评论,我会解决它。

回答by Jesus Rodriguez

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.

在 Angular 中,您不提交表单(好吧,至少以 angular 的方式)。您只需要一个功能,该功能将在您完成表单时执行您想要执行的操作。

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

只需在您的函数中调用该函数,您<button>就可以开始使用了。

Example: plunker

示例:plunker