Nicolas Janel
Nicolas Janel

Reputation: 3075

How to bind the key of a map in Angular

I receive an object which is on server-side a map, i.e. a key-value array. I would like to bind it in an Angular form and be able to modify the value (easy) and the key. Challenge is that when the key is modified, the associated value has to stay linked.

I tried :

<div ng-repeat="(type, value) in estate.extraServices track by $index">
    <input ng-model="type"> <input ng-model="estate.extraServices[type]">
</div>

But when the first input change, a new line is added to the map and the new one is not linked to the new one.

My goal is to avoid using a scope function to resolve this problem, so I ask without many hope, but who knows !

If a binding on a key isn't possible, I would probably change the object structure to an array of Pair object (2 property : key and value)

<div ng-repeat="pair in array">
    <input ng-model="pair.key"> <input ng-model="pair.value">
</div>

Upvotes: 0

Views: 2825

Answers (1)

charlietfl
charlietfl

Reputation: 171679

You can't bind an input to the actual property name. Object property names can't be changed dynamically

Your first example however works fine to update values

<div ng-repeat="(type, value) in estate.extraServices track by $index">
   {{type}} <input ng-model="estate.extraServices[type]">
</div>

As for adding keys you would need to use a different input not bound to that object to add a new key to the object. Then with an event handler use a function that updates the object

Same for removing keys , use an event handler function that would do delete object[key]

Changing to an array of objects with same key name structure would likely be simplest depending on how this object is used

DEMO

Upvotes: 1

Related Questions