Angular:如何使用指令中的表达式通过 id 获取元素? [英] Angular: How to get an element by id with an expression from a directive?

查看:55
本文介绍了Angular:如何使用指令中的表达式通过 id 获取元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

前面的问题很大,所以让我们分解一下.我尝试为 实现类似于本机 的行为.我不能嵌套它们,所以我使用这样的样式:

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>

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

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>

现在我的问题:在 内部,我想在 for 属性中配置元素.假设 foo 内的 $rootScope 中设置了值 "bar" I得到 foo-bar.但是,无论我在哪里尝试(在 compilelinkcontroller 内,有或没有 priority 等.) 特定元素(这里是 <p>)当时还有 test-{{ foo }} ,所以我得到 null使用 getElementById.

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.

如果元素具有包含表达式的 id,我如何获取指令之外的元素?

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

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

(注意:在我的实际应用中,这个问题略有不同.我实际上可以 getElementById 从指令中获取正确的元素,即使 id 包含一个表达式.但是,这仅在特定模板位于 $templateCache 内时才有效.我无法在 JSFiddle 中真正分解它,但 JSFiddle 中的示例非常相似.)

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

推荐答案

你需要在 $timeout 内编写你的 getElementById 代码

You need to write your getElementById code inside $timeout

检查这个更新的fiddle.

这篇关于Angular:如何使用指令中的表达式通过 id 获取元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆