Himmators
Himmators

Reputation: 15006

Use value in Scope to name ng-model?

Assume I have an object that looks like this:

$scope.obj.foo = 'bar';

I want an input-field to have the ng-model='bar'

If I define it like this:

<input ng-model="{{obj.foo}}" />

I get a javascript error

If I define it like this:

<input ng-model="obj.foo" />

the ng-model is obj.foo and the input-element get's populated with the value bar.

How should I write my template in order to achieve an input-field that works like this: Desired outcome:

<input ng-model="bar" />

but fetching the ng-model-name from the scope rather than writing it into the template.

Upvotes: 0

Views: 70

Answers (1)

zs2020
zs2020

Reputation: 54524

You need to use an object anyway for the model, so you can do like this

<input ng-model="obj[myModelName]" />

and then plug in the myModelName with either "foo" or "bar".

Upvotes: 1

Related Questions