简体   繁体   English

AngularJS动态创建和提交表单

[英]AngularJS dynamically create and submit a form

I want to create a form object and submit it inside my controller when a user performs some action. 我想创建一个表单对象,并在用户执行某些操作时将其提交到我的控制器中。 I don't want to show this form on my DOM. 我不想在DOM上显示此表单。

I found a similar question here, but it's based on Jquery. 我在这里找到了类似的问题 ,但这是基于Jquery的。

 $('<form action="form2.html"></form>').appendTo('body').submit();

How can do this using AngularJS. 如何使用AngularJS做到这一点。 Thanks 谢谢

If you REALLY want to send a request by submitting a hidden form, you could create a directive that creates the form, submits it and then immediately removes the form from the DOM again. 如果您确实想通过提交隐藏的表单来发送请求,则可以创建一个指令来创建该表单,然后提交该表单,然后立即将其从DOM中删除。 Like this: 像这样:

app.directive('test', function(){
  return {
    restrict: 'E',
    compile: function(element){
      var form = angular.element('<form action="form2.html" method="POST"></form>');
      element.append(form);

      form[0].submit();

      form.remove();
    }
  };
});

There are other ways you could do this as well though. 不过,还有其他方法可以执行此操作。

But I don't see any reason why you would want to do this, when you could just use $http like this: 但是 ,当您可以像这样使用$http时,我看不出您为什么要这样做的任何原因:

$http.post('form2.html');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM