Angular: How to get an element by id with an expre

2019-07-29 12:42发布

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.)

1条回答
狗以群分
2楼-- · 2019-07-29 13:25

You need to write your getElementById code inside $timeout

Check this updated fiddle.

查看更多
登录 后发表回答