raghuveer ambedkar
raghuveer ambedkar

Reputation: 79

how to keep dynamic ng-model with multiple objects creation

I am getting the html from the server with I am generating the html in the view with ng-repeat like below

<div class="col-lg-6"  ng-repeat="controls in steps.infos">
	<input type="text" ng-model="formData[controls.id]">
</div>

in my controller I have declared a variable $scope.formData = {};. It is all working fine. But here I want to create dynamic new ng-model which creates a new object. Can anyone help me on this how to create multiple object by setting dynamic ng-models in the view like - ng-model="formData.{{$index}}[controls.id]". I want to generate below JSON format dynamically using ng-model. is it possible?

{
   "0":{
      "5":"sdfasf"
   },
   "1":{
      "7":"sdfasf"
   }
}

Thanks in Advance

Upvotes: 0

Views: 1640

Answers (1)

Mohit Tanwani
Mohit Tanwani

Reputation: 6628

Try this

ng-model="formData['field_' + $index]"

If you'e nested loop than you can do something like.

ng-model="formData[$parent.$index]['field_' + $index]"

In your case, this might helps you.

ng-model="formData[$index][controls.id]"

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

myApp.controller('GreetingController', ['$scope', function($scope) {
  $scope.home = {parent: {}};
  $scope.objectsList = [{
                'id':1,
                'name': 'Vikram',
                'Age': '25',
                'sex': 'M'
            }, {
                'id':2,
                'name': 'Quantum',
                'Age': '26',
                'sex': 'F'
            }, {
                'id':3,
                'name': 'Katty',
                'Age': '22',
                'sex': 'F'
            }];
  $scope.getJson = function(home){
    console.log(home);
  }
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<body  ng-app="myApp">
<div ng-controller="GreetingController">
<p ng-repeat="obj in objectsList">
    1st textbox<input type="text" ng-model="home.parent[$index][obj.id]" value="" />
  
  2nd textbox<input type="text" ng-model="home.parent[$index][obj.name]" value="" />
  
  <br/><br/>
</p>
  <button ng-click="getJson(home)">Get Json Object</button>
  {{parent}}
</div>
</body>

Upvotes: 1

Related Questions