Reputation: 195
I made an app using Laravel so most of the pages uses simple HTML Form to send HTTP requests.
I recently decided to use Angular Material to code my front-end, but as all of the input components forces to use ng-model, I want to mimic the behavior of the simple HTML Form Submission using an Angular Controller.
For example: I want this
index.html
<form action="/confirm" method="POST">
<input type="text" name="name">
<input type="submit" value="Submit">
</form>
By using this
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
};
}]);
One solution is to append a hidden input inside the form for each of the inputs outside the form. I don't want to do it that way, it will be very in-efficient.
Any other ways? Thank You.
And it will be great if anyone knows how to handle this for a file input.
Upvotes: 3
Views: 882
Reputation: 5557
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>
Upvotes: 2
Reputation: 355
You could use the $http service to make http calls you code should look like this
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.
});
Upvotes: 0