Angular: 如何使用指令中的表达式通过 id 获取元素?

Angular: How to get an element by id with an expression from a directive?

前面有大量问题,所以让我们分解一下。我尝试实现类似于 <input> 的原生 <label> 的行为。我不能嵌套它们所以我使用这样的样式:

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

在我的例子中,<label> 是自定义指令,<input> 是任意元素。它可能看起来像这样:

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

遗憾的是我的 id 并不是真正的静态。它是一种表达。它可能看起来像这样:

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

现在解决我的问题:在 <custom-directive> 内部,我想获取在 for 属性中配置的元素。假设 foo<custom-directive> 内的 $rootScope 中设置了值 "bar",我得到 foo-bar。但是,无论我在哪里尝试(在 compilelinkcontroller 内,有或没有 priority 等)特定元素(此处为 <p> ) 当时仍然 test-{{ foo }},所以我得到 nullgetElementById

如果它有一个包含表达式的 id,我怎样才能得到指令之外的元素?

这里有一个例子:http://jsfiddle.net/cd6uooze/

(注意:在我的真实世界应用程序中,这个问题略有不同。我实际上可以 getElementById 来自指令的正确元素,即使它 id 包含一个表达式。但是这只有效直到特定模板在 $templateCache 内。我无法在 JSFiddle 中真正分解它,但它与 JSFiddle 中的示例非常相似。)

你需要在里面写你的 getElementById 代码 $timeout

检查此更新 fiddle