gpt4 book ai didi

javascript - angularjs 获取表单 Action 并提交给它

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:46:41 25 4
gpt4 key购买 nike

我有一个表单,我想捕获它的提交,检查数据验证,然后将表单提交给 HTML 表单内的操作。

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


};
});

最佳答案

你应该:

  1. 使用ng-submit表单上的指令
  2. 将表单元素传递给您的save() 方法
  3. 使用$http邮寄服务

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>

关于javascript - angularjs 获取表单 Action 并提交给它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25953541/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com