0

I am trying to bind each element in form to an element in array of objects. What is a good way to do this? Do I need to create client side models and then serialize it? below is jsfiddle on what I am trying to achieve

http://jsfiddle.net/PmChk/1

var app = angular.module('myApp', []);

app.controller('myController', function($scope) {
$scope.TestObject = {
"$id" : "1",
"CreatedOn" : null, 
"FieldValues" : [{
        "$id" : "2",
        "FieldId" : "a1",
        "FieldName" : "FirstName",
        "FieldValue" : "Tom",           
    }, {
        "$id" : "3",
        "FieldId" : "a2",
        "FieldName" : "LastName",
        "FieldValue" : "silver",

    }
]
}    
});

<form class="form-horizontal">
<div ng-app="myApp" ng-controller="myController">   
 <div class="form-group">
      <label for="firstName" class="col-md-4 control-label">First Name</label>
       <div class="col-md-8">
            <input type="text" id="firstName" name="firstName" class="form-control"/>
       </div>
  </div>                            
  <div class="form-group">
       <label for="lastName" class="col-md-4 control-label">Last Name</label>
       <div class="col-md-8">
       <input type="text" id="lastName" name="lastName" class="form-control"/>
 </div>         
 </div>
 <form>

Thanks

1 Answer 1

0

You can use an ng-repeat, and iterate through each item in the array:

<div ng-app="myApp" ng-controller="myController">  
    <div class="form-group" ng-repeat="field in TestObject.FieldValues">
       <label for="lastName" class="col-md-4 control-label">{{field.FieldName}}</label>
       <div class="col-md-8">
       <input type="text" id="lastName" name="lastName" class="form-control" ng-model="field.FieldValue"/>
    </div>
</div>

Updated jsfiddle

This will give you an element for every item in the array, bounded to the corresponding values.

Sign up to request clarification or add additional context in comments.

2 Comments

problem with this is it relies on order of fields in array
Not a problem, you can order them. See here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.