Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angularjs get form action and submit to it

I have a form and I want to catch it submission, check validation of data and than submit form to the action inside the HTML form.

<div ng-controller="contactCtrl">
   <form action="someAction" method="post" name="contactForm" class="clearfix frmContact">
      <div class="one_half">
         <input id="txtName" ng-model="name" value="" class="form-control">
      </div>
      <button ng_click="save($event)" type="submit">Send Message</button>
   </form>
</div>

and my js:

var app = angular.module('bloompyApp', []);

app.controller("contactCtrl", function($scope, $http) {
    $scope.email = "";
    $scope.name = "";
    $scope.message = "";
    $scope.left  = function() {return 100 - $scope.message.length;};
    $scope.clear = function() {$scope.message = "";};
    $scope.save  = function(ev) {
        ev.preventDefault();
        console.log(angular.element(document.querySelector('body')));

        if ($scope.contactForm.$valid) {
            $http.get("/posts/")
                .success(function(response) {console.log(response);});
        }


    };
});
like image 204
Tzook Bar Noy Avatar asked Nov 28 '25 05:11

Tzook Bar Noy


1 Answers

You should:

  1. Use the ng-submit directive on your form
  2. Pass the form element to your save() method
  3. Use the $http service to post

var ctrl = function ($scope, $http, $log) {
$scope.save = function (form) {
    //if (!$scope.contactForm.$valid) return;
    
    var url = form.attributes["target"];
    $log.debug(url);
  
    $http
      .post(url, { email: $scope.email, name: $scope.name })
      .success(function (response) {
        $log.debug(response);
      })
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <form ng-submit="save($element.action)">

    <button type="submit">Send Message</button>
  </form>
</div>
like image 197
Zachary Yates Avatar answered Nov 29 '25 18:11

Zachary Yates



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!