javascript AngularJS:在 HTML 属性中连接 Angular 变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18532396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:18:10  来源:igfitidea点击:

AngularJS: Concatenating Angular variables in HTML attributes

javascripthtmlangularjsconcatenation

提问by trysis

I'm new to AngularJS, but from what I've seen & done so far it is amazing. What I want to do is have an AngularJS binding inside an HTML attribute, but concatenate it with another string. The main place I would do this is classes & id's, as I like to have names like "thisform" & "thisdivid" etc. An example element from my page is:

我是 AngularJS 的新手,但从我目前所见和所做的来看,它是惊人的。我想要做的是在 HTML 属性中有一个 AngularJS 绑定,但将它与另一个字符串连接起来。我会这样做的主要地方是类和 id,因为我喜欢使用“thisform”和“thisdivid”等名称。我页面中的一个示例元素是:

<input type="checkbox" name="tdl_task[]" data-ng-checked="list.default" id="tdl_task_{{ id }}" data-ng-class="{tdl_item: true}" data-ng-true-value="done" data-ng-false-value="not_done" />

I would like it to be something like:

我希望它是这样的:

<input type="checkbox" name="tdl_task[]" data-ng-checked="list.default" id="tdl_task_" + {{ id }} + "" data-ng-class="{tdl_item: true}" data-ng-true-value="done" data-ng-false-value="not_done" />

but without the plusses. I would like to do this without wrapping it in JavaScript or PHP or creating another whole binding in the controller just for that attribute.

但没有优点。我想这样做而不将它包装在 JavaScript 或 PHP 中,或者只为该属性在控制器中创建另一个完整的绑定。

采纳答案by Satyam Koyani

For doing this you have to create one directive. id is provided by html itself you cannot modify its behavior. So create your own custom directive that will take your id and assign this as an id of your html element.

为此,您必须创建一个指令。id 由 html 本身提供,您无法修改其行为。因此,创建您自己的自定义指令,该指令将获取您的 id 并将其分配为您的 html 元素的 id。

To learn more about directive please visit

要了解有关指令的更多信息,请访问

Details study on directives

指令的详细研究

回答by kmcurry

Not sure if this is new in Angular since the question was asked but I had this exact same problem. It turns out that you can get Angular to evaluate + replace the handlebars by preceding it with backslash (), i.e., id="tdl_task_\{{id}}"

不确定这是否是 Angular 中的新问题,因为有人问过这个问题,但我遇到了完全相同的问题。事实证明,您可以通过在其前面加上反斜杠 () 来让 Angular 评估 + 替换把手,即,id="tdl_task_\{{id}}"