2

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.

Paridokht
  • 1,374
  • 6
  • 20
  • 45

2 Answers2

1

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

Martijn Welker
  • 5,575
  • 1
  • 16
  • 26
  • thank you..but it does not solve the problem..and by the way I've tried populating other attributes without using `ng-attr-X` – Paridokht Mar 29 '16 at 06:48
  • Could you put your code in a fiddle/plunker for us to look at ? – Martijn Welker Mar 29 '16 at 06:48
  • Martijn's answer should solve the problem. Did you check you `dev console`? The `id` attribute should be replaced by whatever value is returned by your method. Check this plunker which is close enough to what you need. http://plnkr.co/edit/lxHB7Nl6egebFtiKkbBe – Thomas Sebastian Mar 29 '16 at 06:51
  • @ThomasSebastian, (@the post owner as well) Thanks to both of you..I've just explained how I solved my problem temporarily. – Paridokht Mar 30 '16 at 07:09
0

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.

Community
  • 1
  • 1
Paridokht
  • 1,374
  • 6
  • 20
  • 45