AngularJS form validation: indicate required fields to user -


i form labels display red asterisk next label when corresponding form control has required attribute.

instead of hard coding asterisk, desire way append asterisk label dynamically during page load if label's corresponding input, select or textarea required (the element label corresponds to).

i created directive below, , directive works. there better, more native way accomplish goal? directive finds div.form-group containers , adds red * character after label if corresponding form control inside div.form-group has required attribute.

myapp.directive('labelsrequired',function(){     return {         restrict: 'a',         require: 'ngmodel',         link: function(scope, elem, attrs){             elem.find('div.form-group').each(function(i, formgroup){                 var formcontrols = $(formgroup).find('input, select, textarea');                 console.log(formcontrols)                 if (0 !== formcontrols.length && undefined !== $(formcontrols[0]).attr('required')){                     jlabel = $(formgroup).find('label');                     jlabel.html(jlabel.html()+ "<span class='red-color'>*</span>");                 }             })         }     } }); 

the directive assumes inputs, selects, , textareas inside div.form-group container.

<div class='form-group'>   <label>first name</label><!-- label gets asterisk -->   <input name='fname' required /> </div> <div class='form-group'>   <label>favorite food</label><!-- label not asterisk -->   <input name='favfood'  /> </div> 

building off of corey's answer:

i used compile rather link, saw required attribute not being applied input elements. included select tag dropdowns had.

    app.directive('inputrequired', function () {     return {         restrict: 'a',         compile: function (elem) {             elem.find('label').append("<sup><i class='fa fa-asterisk'></i></sup>");             elem.find('input').attr('required', 'required');             elem.find('select').attr('required', 'required');         }     }; }); 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -