Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mimic a HTML Form request in Angularjs?

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.

like image 765
Jimut Avatar asked Jan 18 '26 19:01

Jimut


1 Answers

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>
like image 54
Kyle Avatar answered Jan 20 '26 08:01

Kyle