Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angularjs required asteriks

Tags:

angularjs

I'd have a directives with a large form with some fields that are required and some that are not. The required fields are marked with required attribute.

I want to pre-pend all the inputs with <span class='something'>*</span> Basically something like this: $("input[required]").prepend(<span class='something'>*</span>)

My still limited understanding of angularjs points me to the compile function of my directives but I am lost when I get there.

Disclaimer: my gut feeling is telling me that doing something like that is not really "the angular" way - that's ok, regardless of whether I end up using this technique or not I'd like to know how to do that. That said I welcome more "angular" suggestions as well.

Thank you!

like image 294
americanslon Avatar asked Apr 24 '14 17:04

americanslon


1 Answers

Whenever DOM manipulation enters the conversation, a directive is the way to go. You're wanting to prepend a * to any inputs with a required attribute, so you want to create a directive from the required attribute. Something like this:

myModule.directive("required", function() {
   return {
       restrict: 'A', //only want it triggered for attributes
       compile: function(element) {
          //could add a check to make sure it's an input element if need be
           element.prepend("<span class='something'>*</span>");
       }
   }
}
like image 143
dnc253 Avatar answered Oct 02 '22 00:10

dnc253