Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually trigger AngularJS validation from a button outside of the form tags?

Given this code:

<div ng-controller="MyCtrl">     <form ng-submit="onSubmitted()">      Header inputs:         <input type="name" ng-model="sample" required/>         <input type="name" ng-model="sampleX" required/>          <input type="submit" value="This submit triggers validation. But I wanted to put this button at the end of the page"/>     </form>      <hr/>      Some other form here. Think line items      <hr />     <a class="btn" ng-click="/* what could should be put here, so this can trigger the firt form's validation, then submit? */">Wanted this submit button to trigger the validation+submit on the form in which this button doesn't belong</a>   </div>   var app = angular.module('myApp', []);  function MyCtrl($scope) {      $scope.onSubmitted = function() {         alert('submitted!');     }; } 

I want the last button to trigger the validation(then submit when things are valid) on first form. As of now, only the button inside the form can trigger that form's validation and submission. Is there any possible way for a button outside the form to do that?

Live test: http://jsfiddle.net/dzjV4/1/

like image 386
Hao Avatar asked Aug 12 '12 07:08

Hao


People also ask

Which of the following can be used to do the validation in AngularJS forms?

AngularJS also holds information about whether they have been touched, or modified, or not. You can use standard HTML5 attributes to validate input, or you can make your own validation functions. Client-side validation cannot alone secure user input. Server side validation is also necessary.

How do we validate data in AngularJS?

AngularJS performs form validation on the client side. AngularJS monitors the state of the form and input fields (input, text-area, select), and notify the user about the current state. AngularJS also holds information about whether the input fields have been touched, modified, or not.

What is $setValidity in AngularJS?

The $setValidity() function is a built-in AngularJS function that is used to assign a key/value combination that can be used to check the validity of a specific model value. The key in this case is “unique” and the value is either true or false.


1 Answers

You can create directive which you can then attach to <a class="btn".... Check this jsfiddle

http://jsfiddle.net/dzjV4/2/

Note that I added to <input type='submit' id='clickMe'... and linked it with link at the bottom <a class='btn' linked="clickMe"...

like image 135
Milan Jaric Avatar answered Sep 19 '22 08:09

Milan Jaric