简体   繁体   中英

How to bind an array of objects and its properties to multiple html inputs with AngularJS?

I'm using AngularJS for binding forms to a Java Script object, the way simple text inputs or checkboxes are associated on the go.

The problem is when I want to have in my main object an array of objects with multiple properties and these objects are dynamically added, or in other words, more objects can be added and so html elements to input their properties.

I'm coding for this site :

These is where objects would be added to an array:

在此输入图像描述

That whole row is equivalent to an object Posgrado and so Especialidad , Título and Cédula are its properties.

Clicking on Añadir button adds an input row (one more object). It can be seen here:

在此输入图像描述

Each of these wil be at professional.data.postgraduates , an array of objects.

How can I, using Angular:

  • Manage the adding of more input rows .
  • Bind each input row to one single object and push it to an array.
  • Finally, bind the array to professional.data.postgraduates .

So far the only clue I have is using an extra Controller for such objects and maybe using some ng-init directives.

Here I got my whole module and markup:

(function() {


        var app = angular.module('PsicologosRegister', ['checklist-model'])

        app.controller('PsicologoController', function() {

            this.psycho = psicologo

            this.print = function() {

                console.log(this.psycho)
            }
        })

        app.controller('PersonalDataController', function() {

            this.data = datos_Personales

        })

        app.controller('ProfessionalDataController', function() {

            this.data = datos_Profesionales
        })

        app.controller('ProfessionalInterestsController', function() {

            this.data = intereses_Profesionales
        })              



        var datos_Personales = {}
        var datos_Profesionales = {}
        var intereses_Profesionales = {}

        var psicologo = {

                            datosPersonales:            datos_Personales,
                            datosProfesionales:         datos_Profesionales,
                            interesesProfesionales:     intereses_Profesionales
        }
})()

<div class="container" id="seccionRegistro1" ng-controller="PersonalDataController as personal">
<form class="form-horizontal" role="form">

<div class="form-group">
    <label for="inputNombre" class="col-xs-2 control-label">Nombre(s)</label>
    <div class="col-xs-10">
      <input type="text" class="form-control" id="inputNombre" placeholder="Nombre(s)" ng-model="personal.data.name" >

    </div>
</div>

<div class="form-group">
    <label for="inputApellidos" class="col-xs-2 control-label">Apellidos</label>
    <div class="col-xs-10">
      <input type="text" class="form-control" id="inputApellidos" placeholder="Apellidos" ng-model="personal.data.lastname">
    </div>
</div>

<div class="form-group">
    <label for="inputEdad" class="col-xs-2 control-label">Edad</label>
    <div class="col-xs-10">
      <input type="text" class="form-control" id="inputEdad" placeholder="Edad" ng-model="personal.data.age">
    </div>
</div>

    <div class="form-group">
    <label for="inputTel" class="col-xs-2 control-label">Teléfono</label>
    <div class="col-xs-10">
      <input type="text" class="form-control" id="inputTel" placeholder="Teléfono" ng-model="personal.data.phone">
    </div>
</div>

<div class="form-group">
    <label for="inputCel" class="col-xs-2 control-label">Celular</label>
    <div class="col-xs-10">
      <input type="text" class="form-control" id="inputCel" placeholder="Celular" ng-model="personal.data.mobile">
    </div>
</div>

<div class="form-group">
    <label for="inputMail" class="col-xs-2 control-label">e-mail</label>
    <div class="col-xs-10">
      <input type="email" class="form-control" id="inputMail" placeholder="e-mail" ng-model="personal.data.email">
    </div>
</div>  

<div class="form-group">
    <label for="inputFB" class="col-xs-2 control-label">Facebook</label>
    <div class="col-xs-10">
      <input type="text" class="form-control" id="inputFB" placeholder="Facebook" ng-model="personal.data.fb">
    </div>
</div>

<div class="form-group">
    <label for="inputDireccion" class="col-xs-2 control-label">Dirección</label>
    <div class="col-xs-10">
      <input type="text" class="form-control" id="inputDireccion" placeholder="Dirección" ng-model="personal.data.address">
    </div>
</div>      

Here is the markup refered in the questions above:

<div class="container" id="seccionRegistro2" ng-controller="ProfessionalDataController as professional">
    <form class="form-horizontal" role="form">

        <div class="form-group">
            <label for="inputAlmaMater" class="col-xs-2 control-label">Egresado de</label>
            <div class="col-xs-10">
              <input type="text" class="form-control" id="inputAlmaMater" placeholder="Egresado de" ng-model="professional.data.almaMater">
            </div>
        </div>              

        <div class="form-group">
            <label for="inputAñoEgreso" class="col-xs-2 control-label">Año de egreso</label>
            <div class="col-xs-10">
              <input type="text" class="form-control" id="inputAñoEgreso" placeholder="Año de egreso" ng-model="professional.data.course">
            </div>
        </div>

        <div class="form-group">
            <label for="inputCedula" class="col-xs-2 control-label">Cédula Profesional</label>
            <div class="col-xs-10">
              <input type="text" class="form-control" id="inputCedula" placeholder="Cédula Profesional" ng-model="professional.data.cedula">
            </div>
        </div>

        <div class="form-group">

            <label for="checkPosgrado" class="col-xs-2 control-label">Estudios de Posgrado</label>

            <div class="Posgrados" ng-init="numPosgrados = 1" ng-repeat="i in numPosgrados">

                <div class="col-xs-2">
                    <select class="form-control inputPosgradoTipo">
                        <option>Especialidad</option>
                        <option>Maestría</option>
                        <option>Doctorado</option>
                    </select>               
                </div>

                <div class="col-xs-4">
                    <input type="text" class="form-control inputPosgradoTitulo" placeholder="Título">                       
                </div>

                <div class="col-xs-3">
                    <input type="text" class="form-control inputPosgradoCedula" placeholder="Cédula">
                </div>

                <div class="col-xs-1">
                    <input type="button" class="form-control btnAñadirPosgrado" value="Añadir">
                </div>
                </div>

        </div>  

This is much easier to accomplish in Angular than the way you are currently doing it.

Create a controller and define the options for the select list, and populate an array of postgraduates (I hardcoded a few, you would be pulling these from a database most likely). Add a function to create a new postgraduate object and push it onto the array.

app.controller('ProfessionalDataController', function($scope) {

  $scope.tipos = [
    'Especialidad',
    'Maestría',
    'Doctorado'
    ];

  $scope.posgrados = [];   

 //If you wanted to assign records from a database, you could do it here.
 //$scope.posgrados = [
 // {tipo: 'Especialidad', titulo: 'titulo 1', cedula: 'cedula 1'},
 // {tipo: 'Maestría', titulo: 'titulo 2', cedula: 'cedula 2'},
 // {tipo: 'Doctorado', titulo: 'titulo 3', cedula: 'cedula 3'}
 //  ];

 $scope.addPosgrado = function(){
  var posgrado = {tipo: 'Especialidad', titulo: 'titulo', cedula: 'cedula'};
  $scope.posgrados.push(posgrado);
 }

In your view, you can create a table and iterate over the array of postgraduates, creating a row for each of them. Wire up a button to call your addPosgrado function.

<body ng-controller="ProfessionalDataController">
  <table>
    <thead>
      <tr>
        <th>Tipo</th>
        <th>Titulo</th>
        <th>Cedula</th>
      </tr>
    </thead>
    <tr data-ng-repeat="p in posgrados">
      <td><select ng-options="t for t in tipos" ng-model="p.tipo"></select></td>
      <td><input type="text" ng-model="p.titulo"/></td>
      <td><input type="text" ng-model="p.cedula"/></td>
    </tr>
  </table>
  <button ng-click="addPosgrado()">Añadir</button>    
</body>

Here's a Plunker

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