How to send data from a form received from an ng-repeat with angularjs

6

Hello, people, maybe my question is not enlightening, but I'll try to elucidate here. I have a code in angularjs and html, this is a form, which receives the data in array / json format, and populates that form, with an ng-repeat, what I need to do is get those fields created with ng- repeat and send to the server when submitting this same form. The code is this:

<form ng-submit="moviments.save()">
    <table>
         <tr ng-repeat="colletion in moviments.data">
             <td><input type="hidden" ng-model="colletion.id"></td>
             <td><input type="text" ng-model="colletion.data"></td>
             <td><input type="text" ng-model="colletion.description"></td>
             <td><input type="text" ng-model="colletion.value"></td>
        </tr>               
</table>
<button type="submit" >Enviar</button>
</form>

"moviments" is a reference for the controller responsible, I already tried to add in ng-model this reference, like this:

<td><input type="text" ng-model="moviments.colletion.data"></td>

but this way ng-repeat does not iterate the array of data.

If anyone can give a light, thank you very much

    
asked by anonymous 04.03.2016 / 18:57

3 answers

1

To submit the post for a form you should use $ http or $ resources of the ngResource module, the latter which is a bit more advanced and also does http request operations. >

You should implement your "moviments" in a factory or service as in the code below.

'strict';
/*** MOCK ***/
var mockData = [{
  'id': 1,
  'data': new Date(),
  'description': 'foo',
  'value': 1.23
}];
var json = JSON.stringify(mockData);
var blob = new Blob([json], {
  type: "application/json"
});
var mockBackEnd = URL.createObjectURL(blob);
//console.log(mockBackEnd);
/*** FIM mock ***/

var app = angular.module('movimentsApp', []);
//Factory moviments
app.factory('moviments', ['$http', function($http) {
  return function moviments() {
    var self = this; //Para que o this não seja confundido dentro das funções.
    self.data = {
      data: []
    };
    //Essa função deve atualizar o this.data;
    self.getData = function() {
      $http.get(mockBackEnd).then(function(ret) {
        self.data = ret.data;
        //console.log(self.data);
      });
    }
    self.delete = function() { /* ... */ }
    self.add = function() {
      self.data.push({
        'id': null,
        'data': new Date(),
        'description': '',
        'value': null
      })
    }
    self.save = function(successCallback, errorCalback) {
      console.info('postData', self.data);
      //Utiliza o post para enviar o post ao seu backend
      var promise = $http.post(mockBackEnd, self.data)
        .then(successCallback || angular.noop)
        .catch(errorCalback || angular.noop);
      return promise;
    }
    //Se quiser inicializar seus dados faça uma chamada ao this.getData dentro da factory.
    self.getData();
    return self;
  }
}]);
app.controller('MainCtrl', ['moviments', '$scope', function(moviments, $scope) {
  $scope.moviments = new moviments();
}]);
<html ng-app="movimentsApp">

<head>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js"></script><linkhref="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>

<body ng-controller="MainCtrl">
  <div class="container">
    <form ng-submit="moviments.save()">
      <table class="table table-striped table-responsive">
        <tr ng-repeat="colletion in moviments.data">
          <td><input type="text" ng-model="colletion.id"></td>
          <td><input type="text" ng-model="colletion.data"></td>
          <td><input type="text" ng-model="colletion.description"></td>
          <td><input type="text" ng-model="colletion.value"></td>
        </tr>
      </table>
      <button type="submit" class="btn btn-primary btn-xs">Enviar</button>
      <button type="button" ng-click="moviments.add()" class="btn btn-success btn-xs">Adicionar</button>
    </form>
  </div>
</body>

</html>

NOTE: Where the "MOCK" tag is a code just to simulate the backend.

The implementation of the $ resource is a bit more extensive, $ http should already be enough to resolve this issue. For other details look at the documentation of AngularJS conform the links I passed.

    
21.09.2017 / 13:58
0

As you have done ng-repeat in your array, each object within this array will have unique values. All you have to do is send via POST to your collection that is moviments.data .

I set the example below as a figment of what you should do, it is very interactive for you to better understand what happens to each object inside the array. Tailor your need.

angular.module('testApp', [])

  .controller('movimentCtrl', ['$scope', function($scope) {

    $scope.moviments = {
      data: [],
      add: function() {
        this.data.push({
          id: '',
          data: '',
          value: '',
          description: '',
        });
      },
      remove: function(index) {
        this.data.splice(index, 1);
      },
      save: function() {
        // O seu post deverá enviar da seguinte forma.

        // $http({
        // method: 'POST',
        // data: this.data,
        // })
        // .then(function(resp) {
        // console.log(resp);
        // });

        console.log(this.data);
      }
    }

    $scope.moviments.add();

  }]);
textarea,
.overflow {
  width: 350px;
  height: 350px;
  overflow: scroll;
}

table {
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script><divng-app="testApp" ng-controller="movimentCtrl">

  <form ng-submit="moviments.save()">
    <table>
      <tr ng-repeat="colletion in moviments.data">
        <td><input type="hidden" ng-model="colletion.id"></td>
        <td><input type="text" ng-model="colletion.data"></td>
        <td><input type="text" ng-model="colletion.description"></td>
        <td><input type="text" ng-model="colletion.value"></td>
        <td>
          <button type="button" ng-click="moviments.add()">Add</button>
          <button type="button" ng-click="moviments.remove($index)" ng-disabled="moviments.data.length == 1">Remove</button>
        </td>
      </tr>
    </table>

    <button type="submit">Salvar</button>

  </form>

  <hr />

  <h3>Data view</h3>

  <div class="overflow">
    <div ng-repeat="collection in moviments.data">
      <h5>Objeto {{$index}}</h5>
      <div>ID: <b>{{collection.id}}</b></div>
      <div>Data: <b>{{collection.data}}</b></div>
      <div>Value: <b>{{collection.value}}</b></div>
      <div>Description: <b>{{collection.description}}</b></div>
    </div>
  </div>

  <hr />

  <h3>Json View</h3>

  <textarea>
        {{moviments.data}}
        </textarea>
</div>
    
21.09.2017 / 16:12
-1

Yesterday I had a similar question and decided thus: ... ng-repeat="i in [] | range:example.QTD"> <input ... ng-model="example.NOME[i]" /> <input ... ng-model="example.MATRICULA[i]" /> <input ... ng-model="example.CPF[i]" /> <input ... ng-model="example.CELULAR[i]" /> ... Basically I generate the repetition based on the amount that the input with the model example.QTD has. Hence, I create the array of repeated inputs with array. So I can save all the data. I hope it has helped:)

    
04.03.2016 / 22:41