在AngularJS上模拟提交和验证到单独的表单

时间:2012-08-19 13:28:50

标签: javascript 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可以实现我的目标?即不使用任何隐藏的提交按钮

1 个答案:

答案 0 :(得分:0)

你在这里没有想到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);
    }
}

无论您是否在表单的范围内,这都将起作用,但您需要在控制器的范围内。