Tzook Bar Noy
Tzook Bar Noy

Reputation: 11677

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);});
        }


    };
});

Upvotes: 3

Views: 22841

Answers (3)

Zachary Yates
Zachary Yates

Reputation: 13386

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>

Upvotes: 6

Endless
Endless

Reputation: 37806

Use ng-submit instead on the form element

"Additionally it prevents the default action (which for form means sending the request to the server and reloading the current page), but only if the form does not contain action, data-action, or x-action attributes."

It will also only run the expressions if the native html5 validation is valid

Upvotes: 0

Sergio Rinaudo
Sergio Rinaudo

Reputation: 2363

I really advice you to follow this page of the docs from the beginning to the end, you'll change your approach to form using AngularJS :)

https://docs.angularjs.org/guide/forms

Upvotes: 0

Related Questions