6

I am new to AngularJS, and am trying to make formatted JSON based on the table tr and td values.

The table tr is auto generated. Once the form is submitted, I try to generate the json values.

After the form is submitted, I need to generate the JSON.

<form>

    <table>
        <!-- Auto generated rows -->
        <tr>
            <td>
            <input type="text" class="form-control" name="tname"  value="">
            </td>
            <td>
            <select ng-model="selection1" class="form-control"  name="ttype" value="">
                <option value="bbb" selected>Test</option>
                <option value="aaa" >Lumpsum</option>
            </select></td>
            <input type="text" class="form-control parsley-success" name="tvalue" >
            </td>
        </tr>
        <tr>
            <td>
            <input type="text" class="form-control" name="tname"  value="">
            </td>
            <td>
            <select ng-model="selection1" class="form-control"  name="ttype" value="">
                <option value="bbb" selected>Test</option>
                <option value="aaa" >Lumpsum</option>
            </select></td>
            <input type="text" class="form-control parsley-success" name="tvalue" >
            </td>
        </tr>
        <tr>
            <td>
            <input type="text" class="form-control" name="tname"  value="">
            </td>
            <td>
            <select ng-model="selection1" class="form-control"  name="ttype" value="">
                <option value="bbb" selected>Test</option>
                <option value="aaa" >Lumpsum</option>
            </select></td>
            <input type="text" class="form-control parsley-success" name="tvalue" >
            </td>
        </tr>
        <tr>
            <td>
            <input type="text" class="form-control" name="tname"  value="">
            </td>
            <td>
            <select ng-model="selection1" class="form-control"  name="ttype" value="">
                <option value="bbb" selected>Test</option>
                <option value="aaa" >Lumpsum</option>
            </select></td>
            <input type="text" class="form-control parsley-success" name="tvalue" >
            </td>
        </tr>
    </table>
   <input type="submit" name="save" value="save"/>
   </form>

I have 3 rows table, so I need to generate 3 object array the json

"data" : [
 {
    "tname":"{tr1 name}",
    "value":"{tr1 tvalue}",
    "ttype":"{tr1 ttype}",
    "index":"index 1"
    },
    {
    "tname":"{tr2 name}",
    "value":"{tr2 tvalue}",
    "ttype":"{tr2 ttype}",
    "index":"index 2"
    },
    {
    "tname":"{tr3 tname}",
    "value":"{tr3 tvalue}",
    "ttype":"{tr3 ttype}",
    "index":"index 3"
    }
]

If I have 10 table rows, that means I need to generate a new row object.

Please, can anyone suggest the correct way to do this in AngularJS?

12
  • what does auto generated mean? Way are all the ng-model's the same? Shouldn't have to do anything except grab one object assigned to all ng-model's when they are set up properly, which they aren't. So main issue is how is table generated? Commented Feb 19, 2016 at 6:03
  • auto generated means - Table row count dynamically will change. Commented Feb 19, 2016 at 6:04
  • Row count is irrelevant... how are they generated? Commented Feb 19, 2016 at 6:05
  • well you could try to create a json object using javascript in the specified structure for respective tr when it is being auto created. Commented Feb 19, 2016 at 6:05
  • @charlietfl - We have textbox in top(i didn't include the html). If I enter the 3 means the three rows will be generate. Once user click the submit button means need to generate the json. Commented Feb 19, 2016 at 6:08

3 Answers 3

1

Solution based on jsFiddle SO.

Example on jsfiddle.

angular.module('ExampleApp', [])
  .controller('firstCtrl', function($scope, $filter) {
    $scope.cloneRow = function(comment) {
      $scope.finalJson.comments.push({});
    };
    $scope.finalJson = {
      comments: [{name:"Basic",type:"",value:"",index:1},
      				  {name:"house rent allowance",type:"",value:"",index:2},
                {}]
    };

    $scope.removeRow = function(index) {
      $scope.finalJson.comments.splice(index, 1);
    };
    $scope.submit = function() {
      var json = JSON.stringify($scope.finalJson.comments);
      console.log(json);
      alert(json);
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="firstCtrl">
    <table>
      <tr ng-repeat="comment in finalJson.comments">
        <td>
          <input ng-disabled="$index<2" type="text" ng-model="comment.name" class="form-control" value="" placeholder="Special Allowance" />
        </td>
        <td>
          <select ng-model="comment.type" class="form-control" name="">
            <option value="">-- Select an option--</option>
            <option value="Percentage" selected>Percentage</option>
            <option value="Percentage">Lumpsum</option>
          </select>
        </td>
        <td>
          <input type="text" ng-model="comment.value" class="form-control parsley-success">
          <input type="hidden" ng-model="comment.index" ng-show="(comment.index=$index) ||1==1" class="form-control parsley-success">
        </td>
        <td>
          <button ng-show="finalJson.comments.length>2 && $index>2" type="button" ng-click="removeRow($index)" class="btn btn-danger" data-type="plus">Minus
            <span class="glyphicon glyphicon-minus"></span>
          </button>
          <button  ng-hide="$index<2" type="button" ng-click="cloneRow()" class="btn btn-success btn-number" data-type="plus">Add
            <span class="glyphicon glyphicon-plus"></span>
          </button>
        </td>
      </tr>
    </table>
    <pre>{{finalJson.comments|json}}</pre>
    <button ng-click="submit()">
      Submit
    </button>
  </div>
</div>

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

1 Comment

This is my jsFiddle.
1

Try this solution jsfiddle.

angular.module('ExampleApp', [])
  .controller('firstCtrl', function($scope) {
    $scope.arr = [];

  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="firstCtrl">
    <div ng-init="arr[0]={firstName:'123',lastName:'123'}">
      <input ng-model="arr[0].firstName">
      <input ng-model="arr[0].lastName">
    </div>
    <div ng-init="arr[1]={firstName:'234',lastName:'234'}">
      <input ng-model="arr[1].firstName">
      <input ng-model="arr[1].lastName">
    </div>
    <div ng-init="arr[2]={firstName:'567',lastName:'567'}">
      <input ng-model="arr[2].firstName">
      <input ng-model="arr[2].lastName">
    </div>
   <pre> json={{arr|json}}</pre>
  </div>
</div>

Updated based on comments

Example jsfiddle, generate rows based on input.

angular.module('ExampleApp', [])
  .controller('firstCtrl', function($scope,$filter) {
    $scope.arr = [];
		$scope.change = function()
    {
    $scope.arr = $filter('range')($scope.arr,$scope.rowCount)
    }
  })
  .filter('range', function() {
    return function(arr, rowCount) {
       rowCount*=1;
      if(!rowCount || Number.isNaN(rowCount))
        return arr;
      console.log(Number.isNaN(rowCount))
      var resArray =arr;
      if (arr.length < rowCount) {
        for (var i = arr.length; i < rowCount; i++)
          resArray.push({});
      } else {
       resArray=[];
       for (var i = 0; i < rowCount; i++)
          resArray.push(arr[i]);
       console.log(resArray);
      }
      return resArray;
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="firstCtrl">
    <input ng-model="rowCount" ng-change="change()">
    <div ng-repeat="item in arr">
      <input ng-model="item.firstName">
      <input ng-model="item.lastName">
    </div>
    <pre>json = {{arr|json}}</pre>
  </div>
</div>

Updated on real needs SO

Example on jsfiddle

angular.module('ExampleApp', [])
  .controller('firstCtrl', function($scope,$filter) {
    $scope.arr = [];
		$scope.addRow = function()
    {
      $scope.arr.push({});
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp">
  <div ng-controller="firstCtrl">
    <div ng-repeat="item in arr">
      <input ng-model="item.firstName">
      <input ng-model="item.lastName">
    </div>
    <button ng-click="addRow()">
    Add row
    </button>
    <pre>json = {{arr|json}}</pre>
  </div>
</div>

Comments

0

Another Solution

angular.module('ExampleApp', [])
  .controller('firstCtrl', function($scope) {
    $scope.data = [];
    $scope.tType = ['test1', 'test2'];
    $scope.rowCount = 5; //number of rows you need
    $scope.range = function(min, max, step) {
      step = step || 1;
      var input = [];
      for (var i = min; i <= max; i += step) {
        input.push(i);
      }
      return input;
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ExampleApp" ng-controller="firstCtrl">
  <form>
    <table>
      <tr ng-repeat="row in range(0,rowCount)">
        <td>
          <input ng-init="data[$index].tname =''" ng-model="data[$index].tname" type="text" class="form-control" name="tname_{{$index}}" value="">
        </td>

        <td>
          <select ng-init="data[$index].tType = ''" ng-model="data[$index].tType" class="form-control" name="ttype_{{$index}}">
            <option ng-selected="true">Select</option>
            <option value="bbb">Test</option>
            <option value="aaa">Lumpsum</option>
          </select>
        </td>

        <td>
          <input type="text" ng-init="data[$index].tValue=''" ng-model="data[$index].tValue" class="form-control parsley-success" name="tvalue_{{$index}}">
        </td>
      </tr>
    </table>
    <pre>json={{data|json}}</pre>
  </form>
</div>

Comments

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.