[英]Simulating a submit and validation to a separate form on AngularJS
如何在按鈕位於其外部的表單上模擬提交和驗證 ?
可以這樣做:
HTML:
<div ng-controller="MyCtrl">
<form ng-submit="onSubmitted()">
Header inputs:
<input type="name" ng-model="sample" required/>
<input type="name" ng-model="sampleX" required/>
<div style="visibility: hidden">
<input type="submit" id="clcikMe" value="This submit triggers validation. But I wanted to put this button at the end of the page"/>
</div>
</form>
<hr/>
Some other form here. Think line items
<hr />
<a class="btn" linked="clcikMe">Wanted this submit button to trigger the validation+submit on the form in which this button doesn't belong</a>
</div>
使用Javascript:
var app = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.onSubmitted = function() {
alert('submitted!');
};
}
app.directive("linked",function(){
return function (scope, element, attrs) {
var id = attrs["linked"];
element.on("click",function(){
document.getElementById(id).click();
});
};
});
但是我想遠離這種方法,它非常笨拙,它通過點擊隱藏的提交按鈕模擬第一個表單上的提交來觸發驗證+提交
AngularJS(甚至普通的javascript)上是否有API可以實現我的目標? 即不使用任何隱藏的提交按鈕
你在這里沒有想到Angular。 沒有人強迫你使用表格ng-submit。 只需使用2個按鈕,每個按鈕都有自己的ng-click="runThisFunction()"
或者只使用相同的函數並傳遞參數。 即:
<button ng-click="submitForm(true)">Validate + Submit</button>
和
<button ng-click="submitForm(false)">Only Validate</button>
然后在你的控制器中:
$scope.submitForm = function(shouldSubmit) {
//run validation here.
//either using $scope.form.name.$valid or ng-model $scope variable
var dataGood = false;
if ($scope.sample === "goodData" && $scope.sample === "alsoGoodData" ) {
//data is good
dataGood = true;
//alert user that data is good!
alert('good job, your data is great!');
}
else {
//data is bad
alert (' data bad, dear padowan');
}
if (!shouldSubmit) return;
//perform $http request to server, or navigate to a different page or whatever
if (dataGood) {
//submit data to server and let the party begin
$http.post('/api/rocknroll/submit', { sample: $scope.sample, sampleX: $scope.sampleX}).then( $scope.handleResponse);
}
}
無論您是否在表單范圍內,這都將起作用,但您需要在控制器的范圍內。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.