angularjs获取表单操作并提交给它 [英] angularjs get form action and submit to it
本文介绍了angularjs获取表单操作并提交给它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个表单,我想捕获它的提交,检查数据的有效性,然后将表单提交给HTML表单内的操作.
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>
和我的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);});
}
};
});
推荐答案
您应该:
- Use the ng-submit directive on your form
- Pass the form element to your
save()
method - 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>
这篇关于angularjs获取表单操作并提交给它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文