Modeling submission and validation in a separate form on AngularJS

How to simulate submit plus validation on a form whose button is outside?

This can be done as follows:

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

But I wanted to stay away from this approach, it is very shabby, it runs a + submit check, simulating the feed in the first form, by clicking on its hidden submit button

Is there an API on AngularJS (or even simple javascript) that will allow me to achieve my goal? That is, without using the hidden submit button

+4
source share
1 answer

You don't think very angular here. Nobody forces you to work with the ng-submit form. Just use 2 buttons each with its own ng-click="runThisFunction()" or just use the same function and go through the parameter. i.e:

 <button ng-click="submitForm(true)">Validate + Submit</button> 

and

 <button ng-click="submitForm(false)">Only Validate</button> 

Then in your controller:

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

This will work regardless of whether you enter the form area, but you must be in the controller area.

0
source

All Articles