Reputation: 20437
I have a UI component that I'm trying to keep flexible by supporting two different data formats.
I'd like to conditionally pick which scope property is paired with the ng-model
of an input
element.
This code does not work, but it expresses my intent:
<input type="text"
ng-model="treeNode.attachedEntity.name || treeNode.name"
/>
The following code works, but duplicates a lot (this example is simple, but in the real application there is a lot of behavior attached to this input)
<!-- Rename File -->
<input ng-if="!treeNode.attachedEntity"
ng-model="treeNode.name"
type="text"/>
<!-- Rename Folder -->
<input ng-if="treeNode.attachedEntity"
ng-model="treeNode.attachedEntity.name"
type="text"/>
The background, if it helps: This models something like a filesystem, where objects are attached to treeNode representing a folder structure. A treeNode without an attached object is a folder. I want a rename action that decides whether to rename the folder or file depending on what object it's operating on.
Any way I can build this so that the template code is simpler? A directive that extends ng-model? An option for ng-model I don't know about? A getter function in the controller that returns the right model?
Thanks!
Upvotes: 1
Views: 4110
Reputation: 5435
yes a getter would be the way to go i think something like
ng-model="getModel(param)[property]"
where getModel would return a reference to the object which propery you want to observe the downside is that you would have to return the objects reference and not the property to keep the link.
something like http://jsfiddle.net/NhPEN/ could illustrate my point. very simple and w/o sense but demonstrate how you can use a function to retrieve an object and use its property as model, you can use other function to generate the property name and make it completely dynamic
Upvotes: 3