1

Bulky question ahead so let's break this down. I try to achieve a similar behavior like the native <label> for <input>. I can't nest them so I use a style like this:

<input type="checkbox" id="test" />
Some other content...
<label for="test">Lorem ipsum</label>

In my case <label> is a custom directive and <input> is an arbitrary elment. It could look like this:

<p id="test">Some element...</p>
Some other content...
<custom-directive for="test">My directive</custom-directive>

Sadly my id isn't really static. It is an expression. It could look like this:

<p id="test-{{ foo }}">Some element...</p>
Some other content...
<custom-directive for="test-{{ foo }}">My directive</custom-directive>

Now to my problem: Inside <custom-directive> I want to get the element configured in the for attribute. Lets say foo has the value "bar"set in the $rootScope inside <custom-directive> I get foo-bar. However no matter where I try it (inside compile, link, controller, with or without a priority, etc.) the specific element (here <p>) has still test-{{ foo }}at that time, so I get null with getElementById.

How can I get the element outside the diretive, if it has an id containing an expression?

Here is an example: http://jsfiddle.net/cd6uooze/

(Note: In my real world app this problem is slightly different. I can actually getElementById the right element from a directive even if it the id contains an expression. However this works only until the specific template is inside the $templateCache. I couldn't really break this down in the JSFiddle, but it the example from the JSFiddle is very similar.)

Pipo
  • 5,623
  • 7
  • 36
  • 46
  • Would you be able to tell us what you want to end result of the directive to be? Once IDs and DOM manipulation start getting used in angularjs, I always assume there's probably a better way to achieve the same result. – rwacarter Jan 16 '15 at 12:59
  • As I said I want to archieve something similar like a native label and inputs, but I don't want to focus something, I want to hide or show other elements on specific events on my directive (like click). Normally I would achieve this with a child directive which registers itself on a parent directive, but this only works if I can nest them. (Like the tabs and panes example on Angulars docs.) – Pipo Jan 16 '15 at 20:24

1 Answers1

3

You need to write your getElementById code inside $timeout

Check this updated fiddle.

Shripal Soni
  • 2,448
  • 17
  • 15
  • So there is no event or callback I can use which indicates when the ID is correctly resolved? :/ `$timeout` always looks like a hack. – Pipo Jan 16 '15 at 20:26
  • No there isn't any event or callback for that and in your scenario you have to execute your dom manipulation code after the binding is done. So we need to use $timeout. – Shripal Soni Jan 16 '15 at 20:35
  • Okay, I'll mark your answer as correct. Sadly there is no better way. – Pipo Jan 16 '15 at 20:54