Abhishek Bansal
Abhishek Bansal

Reputation: 5335

Setting ng-model value dynamically to the value of js variable in AngularJS

Similar questions have bee asked before and I have tried solutions given to them, but my problem is little different.

Lets say I have an array of objects like this in my controller

$scope.objArray = [
  {
    id:1,
    name:"placeholder1"
  },
  {
    id:2,
    name:"placeholder2"
  }
];

now based on this array I am generating a form dynamically like this

  <div ng-repeat="field in fields">
    {{field.field_name}} </br>
    <input type="text" ng-model="field.field_name"><br>
  </div>

here in this form i want ng-model value to be set as placeholder1 and placeholder2 and not like javascript variable like field.field_name because my targets are coming from another source which contains html like below.

<p>this is sample html {{placeholder1}}. again sample html {{placeholder2}} </p>

i don't have those JS variables in here. I could not find any solution which will work this way for me so far.

here is link to plunk: http://plnkr.co/edit/ttaq0l3PDRu4piwSluUX?p=preview

Upvotes: 1

Views: 3363

Answers (1)

dfsq
dfsq

Reputation: 193261

In your case it will look like this:

<div ng-repeat="field in fields">
    {{field.field_name}}
    <br>
    <input type="text" ng-model="$parent[field.field_name]">
    <br>
</div>

Note, that you have to use $parent reference because in your case you want to set property of the outer scope (where objArray is defined), however ngRepeat creates child scopes per iteration, so you need one step up.

Demo: http://plnkr.co/edit/35hEihmxTdUs6IofHJHn?p=info

Upvotes: 2

Related Questions