Angularjs required asteriks


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!

Problem courtesy of: americanslon


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>");
Solution courtesy of: dnc253


input[required], select[required] {
    background-image: url('/img/star.png');
    background-repeat: no-repeat;
    background-position: right;

Image has some 20px space on the right not to overlap with select dropdown arrow

Image is here

Discussion courtesy of: Toolkit

This recipe can be found in it's original form on Stack Over Flow.