在模板angularJs中从控制器填充id属性的值

populate value of id attribute from controller in template angularJs

本文关键字:id 填充 属性 控制器 angularJs      更新时间:2023-09-26

我正在用angularJs写一个directive,下面有一个简单的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" />

但问题是,即使用于测试的<p>标签显示正确的值,input id也没有得到该值
我试过这些id="c.inputId()"id='c.inputId()'id="{{c.inputId()}}"id='{{c.inputId()}}',但都不起作用
有什么想法吗?我的代码出了什么问题,我该如何解决???

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

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

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

问题是在角度绑定尚未完成时读取id,因此document.getElementbyId('#someId')返回null

我在directivelink函数中使用$timeout解决了这个问题
感谢这篇文章。。我不确定这是否是最好的解决方案,我也对我的解决方案不满意。