Reputation: 11677
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
Reputation: 13386
You should:
save()
methodvar 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
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
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