populate value of id attribute from controller in template angularJs

687 Views Asked by At

I am writing a directive with angularJs, with a simple below html template and a contorller as c

template:

<p>Input id : {{c.inputId()}}</p> <!--this is for test,correct value is shown-->
<input id="{{c.inputId()}}" type="text" />

but the problem is that even the <p> tag for test shows correct the value, the input id does not get the value.
I've tried these id="c.inputId()", id='c.inputId()', id="{{c.inputId()}}", id='{{c.inputId()}}', but none of them work.
Any ideas what is wrong with my code and how can I solve this???

EDIT 1
I think I is better to explain that documnet.getElementbyId returns null..maybe It was my mistake that I didn't mentioned it in order to make the question simple and I did not realize that documnet.getElementbyId returns null.

2

There are 2 best solutions below

4
On

You should use ng-attr to use interpolation in attributes, so in your case ng-attr-id="{{c.inputId()}}"

0
On

to @Martijn answer, actually it will work with id and there is no need to use ng-attr-id :)

the problem is reading the id when the angular binding has not completed yet, so document.getElementbyId('#someId') returns null.

I've solved it with using $timeout in link function of my directive
thanks to this post..I am not sure if it is the best solution and also I am not happy with my solution.