我使用Laravel创建了一个应用程序,因此大多数页面都使用简单的HTML表单来发送HTTP请求。
我最近决定使用Angular Material来编写我的前端代码,但由于所有输入组件都强制使用ng-model,我想模仿使用Angular Controller的简单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
};
}]);
一个解决方案是在表单内为表单外的每个输入添加一个隐藏的输入。我不想这样做,效率会非常低。
还有其他方法吗?谢谢。
如果有人知道如何处理文件输入,那将会很棒。
答案 0 :(得分:2)
<强>使用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>
答案 1 :(得分:0)
您可以使用$ 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.
});