0

I am generating json data for multiple elements with angular. I am getting output as

{"field":{"name":{"0":"a","1":"b"},"length":{"0":10,"1":20}}}

I want jsondata to be sophisticated (in array form) such as:

{"field":[{"name":"a", "length":10},{"name":"b", "length":20}]}

How can I achieve this ?

<!DOCTYPE html>
<html>
<head>
<script src="https://rawgit.com/angular/bower-angular/master/angular.min.js"></script>
<meta charset=utf-8 />  
</head>
<body>

  <div ng-app="mainApp" ng-controller="JsonController as ctrl">

   <div ng-repeat="a in [1,2] track by $index">
     <input type="text" ng-model="task.field['name'][$index]">
     <input type="number" ng-model="task.field['length'][$index]"> 
   </div>

    <pre>
    {{task}}
    </pre>
  </div>

<script>
  (function() {
    angular.module("mainApp", []).controller("JsonController", function($scope) {
          $scope.task = {};

          });
    }());
</script>

</body>
</html>

1 Answer 1

1
<div ng-repeat="a in [1,2] track by $index">
  <input type="text" ng-model="task.field[$index].name">
  <input type="number" ng-model="task.field[$index].length"> 
</div>

$scope.task = {
    field: []
};

Although I don't like this approach at all. Why don't you create your objects upfront in the controller, and just iterate over them:

<div ng-repeat="t in task.field">
  <input type="text" ng-model="t.name">
  <input type="number" ng-model="t.length"> 
</div>

$scope.task = {
    field: [{}, {}]
};
Sign up to request clarification or add additional context in comments.

2 Comments

actually my example is minified version taken from some module just to illustrate.
Please correct in your first block $scope.task = { field: []};

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.