< Back to AngularJS, Coding

Forms in Angular

Most of the code is in the HTML. Here are the main points:

On the ‘form’ element itself add ‘novalidate’ attribute to turn off the default validation that some browsers have, have a name, as well as ‘ng-submit=”formName.$valid && Ctrl.submitFunction()”. The last bit does the submit function (not the submit button), checks if the form with the name is valid and if so does the function in the controller js.

‘ng-model’ attribute tells angular which property in the Controller this input field represents. It binds the form element’s result to a value that lets another area on the page auto update when the form’s inputs are changed.

Adding ‘required’ to any form elements make it so you have fill in the field properly for the form to be valid.

To make radio buttons required use ng-required=”!Ctrl.curFormEntry.property”. curFromEntry would be declared as a variable in the Controller like so this.curFromEntry = {}; and represents all the data in the current form.

Angular also has build in classes that tell whether a field has been touched and whether it’s currently active or not. You can use css to show this info to the user like so:

.ng-invalid.ng-dirty{
 border-color: red;
}

.ng-valid.ng-dirty{
 border-color:green;
}

View the demo

Download the demo

 

 

Be Sociable, Share!

Leave a Reply

Your email address will not be published. Required fields are marked *