AngularJS:动态ng绑定属性
问题描述:
我正在做一个使用select2的指令。在我的屏幕中,我将有许多select2对象,所以这就是为什么我想使用一个指令,我可以重复使用它很多次。AngularJS:动态ng绑定属性
这是指令:
<div class='form-group'>
<p>{{title}}</p>
<ui-select ng-model="selectedItem" on-select="onChange($item);" theme="bootstrap">
<ui-select-match placeholder="{{placeholder}}">
{{selectedItem.state}}
</ui-select-match>
<ui-select-choices repeat="item in items | filter: $select.search">
<span ng-bind="item.state"></span>
</ui-select-choices>
</ui-select>
然后,我可以做到这一点通过我的index.html文件中的参数:
<strainer-select
items="strainer.states"
selectedItem="strainer.selectedState"
handler="onStateChange"
title="Estados"
placeholder="Escolha um Estado"
></strainer-select>
我的问题是:在选择2我需要通知我的对象属性“绑定”并在视图中显示,如下所示:
{{selectedItem.state}}
但是,当然,属性'状态'将不可用于所有对象。如果我有一个“城市”对象,它可以是“cityName”,或者如果我想显示用户,它可能只是“名称”或“用户名”。
我想避免做一个拦截器,并修改我的所有数据复制属性只是为了适应数据中的通用“名称”。如果我的目标是:
{
state: "Sao Paulo",
uf: "SP"
}
我不想将其更改为:
{
state: "São Paulo",
uf: "SP",
name: "São Paulo" // replicated from "state" property
}
强制到我的指令内使用。
所以,我已经试过动态传递的绑定属性名的指令是这样的:
<strainer-select
items="strainer.states"
selectedItem="strainer.selectedState"
handler="onStateChange"
title="Estados"
placeholder="Escolha um Estado"
bindName="state"
></strainer-select>
而在该指令像这样使用它:
<span ng-bind="item.{{bindName}}"></span> // didnt work
<span ng-bind="item[{{bindName}}]"></span> // didnt work
<span ng-bind="item['{{bindName}}']"></span> // didnt work
和UI选 - 匹配看起来最差....
<ui-select-match placeholder="{{placeholder}}">
{{selectedItem["{{bindName}}"]}} // didnt work
</ui-select-match>
但没有成功。
有没有人有线索我如何动态更改ng-bind使用的属性名称?
谢谢。
答
尝试
<span ng-bind="item[bindName]"></span>
<ui-select-match placeholder="{{placeholder}}">
{{selectedItem[bindName]}}
</ui-select-match>
虽然在ng-bind
你不需要逃避使用你正在编写原始代码的变量 - 因此你为什么需要引用和字符串的直接用途。
感谢工作,但没有与任何“绑定”名称中的东西。我猜Angular引擎可能会以某种方式解析“绑定”这个词。所以我最终'''fillable''': '''的 \t \t \t {{将selectedItem [可填写]}} \t \t'''和'''span_ng-bind =“item [fillable]”>>'''。 谢谢。 –
ppalmeida
只是为了补充信息,以防止任何人坠入此处:在名称中“绑定”某物没有问题。不使用HTML中的“绑定名称”,而是使用“绑定名称”。在这里检查AngularJS文档:https://docs.angularjs.org/guide/directive(规范化部分:最佳实践:优先使用以短划线分隔的格式(例如ngBind的ng-bind)。)。谢谢。 – ppalmeida