【问题标题】:populate value of id attribute from controller in template angularJs从模板angularJs中的控制器填充id属性的值
【发布时间】:2016-07-16 13:57:14
【问题描述】:

我正在写一个directiveangularJs,下面是一个简单的html template 和一个contorller as c

模板:

<p>Input id : {{c.inputId()}}</p> <!--this is for test,correct value is shown-->
<input id="{{c.inputId()}}" type="text" />

但问题是即使&lt;p&gt; 测试标签显示正确的值,input id 也没有得到值。
我已经尝试过这些id="c.inputId()"id='c.inputId()'id="{{c.inputId()}}"id='{{c.inputId()}}',但它们都不起作用。
任何想法我的代码有什么问题,我该如何解决?

编辑 1
我想我最好解释一下 documnet.getElementbyId 返回 null ..也许这是我的错误,我没有提到它是为了让问题很简单,我没有意识到documnet.getElementbyId 返回null。

【问题讨论】:

    标签: javascript html angularjs angularjs-controlleras controlleras


    【解决方案1】:

    您应该使用ng-attr 在属性中使用插值,所以在您的情况下是ng-attr-id="{{c.inputId()}}"

    【讨论】:

    • 谢谢..但它不能解决问题..顺便说一句,我尝试填充其他属性而不使用ng-attr-X
    • 你能把你的代码放在一个小提琴/plunker中让我们看看吗?
    • Martijn 的回答应该可以解决问题。你检查过你dev console吗? id 属性应替换为您的方法返回的任何值。检查这个足够接近你需要的东西。 plnkr.co/edit/lxHB7Nl6egebFtiKkbBe
    • @ThomasSebastian,(@the post owner as well)谢谢你们两个......我刚刚解释了我是如何暂时解决我的问题的。
    【解决方案2】:

    对@Martijn 的回答,实际上它可以与id 一起使用,并且不需要使用ng-attr-id :)

    问题是在角度绑定尚未完成时读取 id,所以document.getElementbyId('#someId') 返回空值。

    我已经通过在我的 directivelink 函数中使用 $timeout 解决了这个问题
    感谢this post..我不确定这是否是最好的解决方案,而且我对我的解决方案不满意。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-09
      • 2016-07-11
      • 2015-04-05
      相关资源
      最近更新 更多