简体   繁体   中英

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.

I found a similar question here, but it's based on Jquery.

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

How can do this using 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. 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.post('form2.html');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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