2

I would like to know how to dynamically add attribute or property to a specific mark-up in my template. I have my directive like this:

app.directive('myDirective', function() { return { restrict: 'A', template: '<div><label>Label: </label><input id="my-id" type="text" attr="attrValue"/></div>' }; }); 

Question 1: How would I place attr="attrValue" specifically on input element / mark-up?

Suppose I want to write:

<my-directive ... readonly></my-directive> 

Question 2: How can I pass readonly property to the input element in the template?

app.directive('myDirective', function() { return { restrict: 'A', template: '<div><label>Label: </label><input id="my-id" type="text" readonly/></div>' }; }); 
1
  • This is actually not so simple to solve. I had a similar use case of creating a <label> ed input and ended up doing quite a compile function for it. Any way, the solution for me was to create a directive that wraps the <input/> element I wanted to modify like <labeled-input><input ... /></labeled-input> Commented Dec 18, 2014 at 8:54

1 Answer 1

2

The template property of directive configuration can be a function that receives element and attributes as arguments and returns the template (see documentation). You can then use these data when constructing the template:

.directive('...', function () { return { template: function (tElement, tAttrs) { return '... <input ...' + (tAttrs.readonly ? ' readonly' : '') + '> ...'; }, // ... }; }); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.