Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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

share|improve this question

1 Answer 1

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.

share|improve this answer
    
problem with this is it relies on order of fields in array –  user1627701 Feb 28 '14 at 19:04
    
Not a problem, you can order them. See here –  apohl Feb 28 '14 at 20:55

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.