简体   繁体   中英

How to save all rows of a dynamic table in AngularJS?

I am trying to add the rows dynamically for one of the variables which is of type String array in my db. But it only saves the last value entered in the row rather than saving all of them in an array. Below is my view code:

<div class="row" ng-class='{red:true}'>
  <label for="remedy">Remedy</label>
</div>

<input name="remedy" id="remedy" ng-model="error.remedy" required>


<br/>
<div class="row" ng-class='{red:true}'>
  <a href="#!/errorcreate"  class="btn btn-primary btn-small" ng-click="addRemedyRow()" ng-class='{red:true}'>Add Row</a></div>
<br/>

<table style="width:100%">
  <thead>
  <tr>
  <th ng-class='{red:true}'>Remedy</th>

</tr>
</thead>
<tbody>
<tr ng-repeat="rowContent in remedyrows">
  <td>{{rowContent.remedy}}</td>

  </tr>
</tbody>
</table>
{{error.remedy}}
<button type="submit" class="btn btn-default">Create</button>
<a href="#!errorinput" class="btn btn-default">Cancel</a>

And this is the code in javascript:

$scope.remedyrows = [];
$scope.addRemedyRow = function() {
  $scope.remedyrows.push({
    remedy: $scope.error.remedy
  });

Below is the output I am receiving (in a screenshot):

在此处输入图片说明

I added dsdfg as second row and my final error.remedy value just shows dsdfg rather than showing an array of both values : [wdssdsd,dsdfg] . error is the main document of which remedy is one of the fields of type String array.

Any ideas on how to achieve this?

Instead of error.remedy , which is used as holder for future remedyrow , use intermediate variable output for displaying results and sending them to the server:

Javascript:

$scope.output = $scope.remedyrows.map(function(x) { return x.remedy; });
$http({data: $scope.output, method: 'POST', url: url});

HTML:

{{output | json}}

you could have achieved it by following way:

 $scope.remedyrows = [];
    $scope.output;
    $scope.addRemedyRow = function() {
      $scope.remedyrows.push({
        remedy: $scope.error.remedy
      });
     $scope.output = $scope.remedyrows.toString();
    }

and in html

{{output}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM