I am doing a directive using select2. In my screen I will have many select2 objects, so this is why I want to use a directive that I can reuse it many times.
This is the directive:
<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>
Then I can do this to pass the parameters in my index.html file:
<strainer-select
items="strainer.states"
selectedItem="strainer.selectedState"
handler="onStateChange"
title="Estados"
placeholder="Escolha um Estado"
></strainer-select>
My problem is: in select2 I need inform a property of my object to "bind" and be displayed in the view, like so:
{{selectedItem.state}}
But, of course, the property 'state' will not be available in all objects. If I have a "city" object it can be "cityName" or if I want display users it could be just "name" or "userName".
I want avoid to make a interceptor and modify all my data to replicate properties just to fit a generic "name" in the data. If my object is:
{
state: "Sao Paulo",
uf: "SP"
}
I do not want change it to:
{
state: "São Paulo",
uf: "SP",
name: "São Paulo" // replicated from "state" property
}
jus to use inside my directive.
So, I've tried pass the bind property name dynamically to the directive like this:
<strainer-select
items="strainer.states"
selectedItem="strainer.selectedState"
handler="onStateChange"
title="Estados"
placeholder="Escolha um Estado"
bindName="state"
></strainer-select>
And use it in the directive like this:
<span ng-bind="item.{{bindName}}"></span> // didnt work
<span ng-bind="item[{{bindName}}]"></span> // didnt work
<span ng-bind="item['{{bindName}}']"></span> // didnt work
And the ui-select-match looks worst....
<ui-select-match placeholder="{{placeholder}}">
{{selectedItem["{{bindName}}"]}} // didnt work
</ui-select-match>
but with no success.
Does anyone has a clue how I can dynamically change the property name used by ng-bind?
Thank you.
Try
<span ng-bind="item[bindName]"></span>
<ui-select-match placeholder="{{placeholder}}">
{{selectedItem[bindName]}}
</ui-select-match>
Whilst in ng-bind
you do not need to escape the use of variables you are writing raw code - hence why you need to quote and direct usages of strings.