Add new element to array

5

I have a multi-contact directory, where each contact can have one or more dynamic fields. You can define the name of these fields, and they are different between the contacts.

For example, if Contato 1 has the campo 1 field, Contato 2 will not have this field, unless it is added manually.

My multiple contact insertion works correctly after adding the dynamic fields to a single user . The configuration of the dynamic field insertion occurs in a modal.

However, the moment I try to insert a new field in the second contact , and correctly fill in the modal, I get a push is undefined . . >

HTML

<div ng-repeat="contato in contatos" class="form-group"> <div class="col-sm-10"> <h4><b><i>Contato {{$index + 1}}</b></i></h4> <label for="nomeContato">Nome:</label> <input type="text" name="nomeContato" id="nomeContato" class="form-control" ng-model="contato.nome"> <br> <div class="control-group"> <select selectize="single.options" placeholder="Selecionar uma ag&ecirc;ncia" ng-model="contato.agencia" options="listaAgencias"></select> </select> </div> <div ng-repeat="dado in contato.dados"> <label for="campoValor">{{dado.campo}}</label> <input type="text" name="dadoValor" id="dadoValor" class="form-control" ng-model="dado.valor"> <button type="button" class="btn btn-xs btn-default" ng-click="excluirCampo"> <span class="glyphicon glyphicon-remove"></span> </button> </div> <div align="right"><button type="button" class="btn btn-xs btn-primary" ng-click="novoCampo($index)">Inserir novo campo</button></div> </div> </div> <div align="right"> <button type="button" class="btn btn-xs btn-primary" ng-click="novoContato(contato.nome, contato.agencia, dado)"> <span class="glyphicon glyphicon-plus"></span> </button> <button type="button" class="btn btn-xs btn-danger" ng-click="excluirContato()" ng-disabled="contatosVazio()"> <span class="glyphicon glyphicon-minus"></span> </button> </div>

Controller.js

oknok.controller('veiculoController', function ($scope, $q, $timeout, $modal, $log, veiculosAPI, agenciasAPI, contatosAPI) {
  $scope.erroAoSalvar = false;
  $scope.formularioValido = false;
  $scope.salvoComSucesso = false;
  $scope.listaAgencias = [];
  $scope.tipo = "Simples";
  $scope.single = {
    options: {
      valueField: 'nome',
      labelField: 'nome',
      searchField: ['nome']
    }
  };
  $scope.contatos = [{
    nome: "",
    agencia: "",
    dados: []
  }];
  var $mySelect = "";

  agenciasAPI.getAgencias().success(function (data) {
    var embedded = data._embedded;
    $scope.listaAgencias = embedded.agencias;
    $mySelect = $('#select-tools').selectize({
      maxItems: null,
      valueField: 'nome',
      labelField: 'nome',
      searchField: 'nome',
      options: embedded.agencias,
      create: false
    });
  }).catch(function (error) {
    alert("Opsss! Erro ao obter listagem de agencias");
  });

  $scope.novoContato = function (nome, agencia, dados) {
    //Adiciona novo contato
    $scope.contatos.push({
      nome: nome,
      agencia: agencia,
      dados: dados
    });
    agenciasAPI.getAgencias().success(function (data) {
      var embedded = data._embedded;
      $scope.listaAgencias = embedded.agencias;
    }).catch(function (error) {
      alert("Erro ao adicionar novo contato");
    });
  };

  $scope.excluirContato = function () {
    var ultimoItem = $scope.contatos.length - 1;
    $scope.contatos.splice(ultimoItem);
  };

  $scope.contatosVazio = function () {
    if (!($scope.contatos.length <= 1)) {
      return false;
    } else {
      return true;
    }
  };

  $scope.novoCampo = function (index) {
    var modalInstance = $modal.open({
      animation: $scope.animationsEnabled,
      templateUrl: 'myModalContent.html',
      controller: 'ModalInstanceCtrl',
      size: '',
      resolve: {
        index:  function () {
          return index
        }
      }
    });

    modalInstance.result.then(function (result) {
      try{
        //Aqui ocorre undefined
        $scope.contatos[result.index].dados.push({
          campo: result.nomeCampo,
          valor: ""
        });
      }catch(error){
        console.log(error);
      }
    }, function () {
      $log.info('Modal dismissed at: ' + new Date());
    });
  };

  $scope.toggleAnimation = function () {
    $scope.animationsEnabled = !$scope.animationsEnabled;
  };

});

oknok.controller('ModalInstanceCtrl', function ($scope, $modalInstance, contatosAPI, index){
  $scope.animationsEnabled = true;

  $scope.ok = function () {
    $modalInstance.close({nomeCampo: $scope.nomeCampo, index: index});
  };

  $scope.cancel = function () {
    $modalInstance.dismiss('cancel');
  };

});
    
asked by anonymous 28.07.2015 / 20:02

1 answer

2

The problem is that when calling the novoContato(contato.nome, contato.agencia, dado) method, the dado variable is probably coming from undefined or null . Note that it is out of ng-repeat , and therefore contains an invalid value.

When it is then assigned in the excerpt:

$scope.contatos.push({
  nome: nome,
  agencia: agencia,
  dados: dados
});

... the field dados instead of having a array , has undefined (or null ).

So when the push method is called later, it will not exist in the variable and therefore the error.

In addition to being unidefined , it is not necessary to pass the values of nome and agencia to the new contact, angularJS already changes that element dynamically. You just need to enter a new element to create a new contact:

$scope.novoContato = function () {
        //Adiciona novo contato
        $scope.contatos.push({
            nome: "",
            agencia: "",
            dados: []
        });
        agenciasAPI.getAgencias().success(function (data) {
            var embedded = data._embedded;
            $scope.listaAgencias = embedded.agencias;
        }).catch(function (error) {
            alert("Erro ao adicionar novo contato");
        });
    }; 

I hope I have helped.

    
29.07.2015 / 04:46