如何在Angularjs中模拟HTML表单请求

How to mimic a HTML Form request in Angularjs?

本文关键字:HTML 表单 请求 模拟 Angularjs      更新时间:2023-09-26

我使用Laravel制作了一个应用程序,所以大多数页面都使用简单的HTML表单来发送HTTP请求。

我最近决定使用Angular Material来编写我的前端代码,但由于所有的输入组件都强制使用ng模型,我想使用Angular控制器来模仿简单的HTML表单提交的行为。

例如:我想要这个

index.html

<form action="/confirm" method="POST">
    <input type="text" name="name">
    <input type="submit" value="Submit">
</form>

使用此

index.html

<input type="text" name="name" ng-model="name">
<form action="/confirm" method="POST" ng-submit="submit($event)">
    <input type="submit" value="Submit">
</form>

app.js

var app = angular.module('MyApp', []);
app.controller('AppController', ['$scope', function($scope){
    $scope.submit = function(e){
        e.preventDefault();
        var url = e.currentTarget.getAttribute('action');
        var data = {
            name : this.name
        };
        // Some code here that I can't figure out
        // Which will mimic the simple HTML Form Submission
    };
}]);

一个解决方案是为表单外的每个输入在表单内附加一个隐藏的输入。我不想这样做,这将非常有效。

还有别的办法吗?非常感谢。

如果有人知道如何处理文件输入,那就太好了。

Javascript:

app.controller("MainCtrl", ["$scope", "$http", function($scope, $http) {
  $scope.name = null;
  $scope.submitForm = function(name) {
    //submitting form items depend on what your /confirm endpoint is expecting
    //is it expecting JSON, form data in the body, etc?
    //JSON
    var payload = {
        name: name
    };
    //submitting via FormData
    //var payload = new FormData();
    //payload.append("name", name);
    //use $http to post to server
    $http.post('/confirm/', payload).then(function(response) {
        //success
    }, function() {
        //an error has occurred
    });
  }
}]);

HTML:

<form id="myForm" name="myForm" ng-submit="submitForm(name)">
    <!-- bind model to input using ng-model -->
    <input required type="text" ng-model="name" />
    <button ng-disabled="myForm.$invalid" type="submit" ng-click="submitForm(name)">Submit</button>
</form>

您可以使用$http服务进行http调用,您的代码应该看起来像这个

var url = e.currentTarget.getAttribute('action');
var data = {
   name : this.name
};
$http({
  method: url,
  url: '/confirm',
  data:data
}).then(function successCallback(response) {
  // this callback will be called asynchronously
  // when the response is available
}, function errorCallback(response) {
  // called asynchronously if an error occurs
  // or server returns response with an error status.
});