Search code examples
jqueryhtmlangularjsangular-directive

Angular directive to append asterisk in label text


As found out in SO, we can create a custom directive to append required validation asterisk for an element as specified below:

mod.directive("mandatory", function() {
       return {
           restrict: 'A',
           compile: function(element) {
              element.after("*");
           }
       };
    });

I've one simple label tag as follows:

<label mandatory>Name</label>

What it does is it creates the following html content as follows:

 <label mandatory>Name</label>*

What I want is the following html content:

<label mandatory>Name*</label>

I've tried the .text, .html, .appends functions of the element, but it didn't reflect any changes.

Any suggestions will be appreciated.


Solution

  • You may want to set the text in this way:

    mod.directive("mandatory", function() {
           return {
               restrict: 'A',
               compile: function(element) {
                  element.text(element.text() + "*");
               }
           };
        });
    

    However, instead of manipulating the element directly, I would opt for a template or something like that.