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

Asked

Viewed 1,020 times

6

Hello, folks maybe my question is not enlightening, but I’ll try to enlighten here. I have a code in Angularjs and html, if it is a form, which receives the data in array/json format, and populates this form, with an ng-repeat, what I need to do is to take these 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 to the controller responsibly, I have tried to add in ng-model this reference, thus:

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

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

If anyone could shed some light, I’d really appreciate it

  • You want to send, through Submit, only the data of a single Object, is that it? For example, send only what is inside the Collection of one of the ngRepeat iterations, correct?

3 answers

1


To submit a form post you must use the service $http or $Resources ngResource module, the latter which is a bit more advanced and also does http requests.

You must 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>
  <link href="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 only to simulate the backend.

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

0

How did you do the ng-repeat in your array, each object within this array will have unique values. All you need to do is send via POST your collection which is moviments.data.

I set the example below as a figuration of what you should do, it is very interactive for you to better understand what happens to each object within the array. Adapt to 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>

<div ng-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>

-1

Yesterday I had a similar doubt and solved so: ... 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]" /> ... I basically repeat based on the amount the input with the example.QTD model has. Then, I create the model of repeated inputs with array. So I can save all the data. I hope it helped :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.