How to check, for each item entered in the $ scope.items [], if the fields were filled

1

How to check, for each item entered in $ scope.items [], have Phone and CPF been filled in?

Desired scenario:

→ The user must enter at least 1 item, if negative, clicking on "Send" will display an "alert" [ALREADY IMPLEMENTED]

→ When you click "Submit" and the user did not fill in the Phone and CPF fields, an "alert" should be displayed for each item entered. [PROBLEM]

var app = angular.module('app', []);
    app.controller('controlador', function($scope, $http) {
	$scope.user = {};
    $scope.produtoTrib = {};
	$scope.items = [];
	var sum = 1;
	
	$scope.addItem = function (user){
			$scope.items.push({
				nome: $("input[name='nome']").val(),
				email: $("input[name='email']").val(),
				soma: sum++
			});
		  user.nome = '';
		  user.email = '';	
	};
      
     
    $scope.addTributos = function (produto){
        $scope.produtoTrib = produto;
	};
    
   $scope.submitForm = function() {
       if(sum <= 1){
         alert("Insira no mínimo 1 (um) item.");  
       }
   }
   
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script><scriptsrc="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><bodyng-app="app" ng-controller="controlador">

<form ng-submit="submitForm()">
    <label>Nome: </label><input type="text" name="nome" ng-model="user.nome" style="width:100px">
    <label>E-mail: </label><input type="text" name="email" ng-model="user.email" style="width:100px">
    
    <input type="text" hidden name="email" ng-model="user.telefone">
    <input type="text" hidden name="email" ng-model="user.cpf">
    
    <input type="button" value="Adicionar" ng-click="addItem(user)" />
    <input type="submit" value="Enviar"/>
</form>
<br />

<div ng-repeat="item in items track by $index">
ID: {{item.soma}}<br />
Nome: {{item.nome}}<br />
E-mail: {{item.email}}<br /><br />
<!-- {{item.telefone}} - {{item.cpf}} -->
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#myModal" ng-click="addTributos(item)">Tributos</button>
<hr />
</div>

<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Tributos</h4>
      </div>
      <div class="modal-body">
        <label>Telefone: </label><input type="text" name="telefone" ng-model="produtoTrib.telefone">
        <label>CPF: </label><input type="text" name="cpf" ng-model="produtoTrib.cpf">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Atualizar</button>
      </div>
    </div>

  </div>
</div>

</body>
    
asked by anonymous 13.01.2017 / 16:52

2 answers

1

Add a function to validate fields before running push .

Ex:

var validar = function() {

    if(!$scope.myForm.nome.$valid) {
        alert('Digite o nome!');
        return false;   
    };

    if(!$scope.myForm.email.$valid) {
        alert('Digite o email!');
        return false;   
    };
    return true;
}

$scope.addItem = function (user){
    if(validar()){
        $scope.items.push({
            nome: $("input[name='nome']").val(),
            email: $("input[name='email']").val(),
            soma: sum++
        });
      user.nome = '';
      user.email = '';
    }               
};

Assigning a name to the form element will make it easier to use AngularJS validation, in this example I used myForm and include novalidate to not perform HTML5 validation.

<form name="myForm" ng-submit="submitForm()" novalidate>

The validation of AngularJS uses the required attribute of HTML5 to specify that the field should be filled:

Before:

<input type="text" name="nome" ng-model="user.nome" style="width:100px">
<input type="text" name="email" ng-model="user.email" style="width:100px">

Then:

<input type="text" required name="nome" ng-model="user.nome" style="width:100px">
<input type="text" required name="email" ng-model="user.email" style="width:100px">

Use the element input[type=hidden] itself and change the name of the elements input[name=email] to avoid conflicts during validation:

Before:

<input type="text" hidden name="email" ng-model="user.telefone">
<input type="text" hidden name="email" ng-model="user.cpf">

Then:

<input type="text" hidden  name="telefone" ng-model="user.telefone">
<input type="text"  hidden name="cpf" ng-model="user.cpf">

And to check if any item of $scope.items is with the CPF or Phone missing, run for and scroll through the items by checking:

$scope.submitForm = function() {
   if(sum <= 1){
     alert("Insira no mínimo 1 (um) item.");
     return false;  
   }
   for (var i = $scope.items.length - 1; i >= 0; i--) {
     var item = $scope.items[i];
     if(!$scope.items[i].cpf) {
      alert('Por gentileza, preencha o CPF de '+item.nome);
      return false;
     }         
     if(!$scope.items[i].telefone) {
      alert('Por gentileza, preencha o telefone de '+item.nome);
      return false;
     }
   }

}

Result:

var app = angular.module('app', []);
    app.controller('controlador', function($scope, $http) {
	$scope.user = {};
    $scope.produtoTrib = {};
	$scope.items = [];
	var sum = 1;
	
	var validar = function() {

		if(!$scope.myForm.nome.$valid) {
            alert('Digite o nome!');
            return false;	
        };

        if(!$scope.myForm.email.$valid) {
            alert('Digite o email!');
            return false;	
        };
    	return true;
    }

	$scope.addItem = function (user){
		if(validar()){
			$scope.items.push({
				nome: $("input[name='nome']").val(),
				email: $("input[name='email']").val(),
				soma: sum++
			});
		  user.nome = '';
		  user.email = '';
		}
				
	};
      
      
    $scope.addTributos = function (produto){
        $scope.produtoTrib = produto;
	};
    
   $scope.submitForm = function() {
   if(sum <= 1){
     alert("Insira no mínimo 1 (um) item.");
     return false;  
   }
   for (var i = $scope.items.length - 1; i >= 0; i--) {
   	 var item = $scope.items[i];
     if(!$scope.items[i].cpf) {
      alert('Por gentileza, preencha o CPF de '+item.nome);
      return false;
     }         
     if(!$scope.items[i].telefone) {
      alert('Por gentileza, preencha o telefone de '+item.nome);
      return false;
     }
   }
   }
   
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body ng-app="app" ng-controller="controlador">

<form name="myForm" ng-submit="submitForm()" novalidate>
    <label>Nome: </label><input type="text" required name="nome" ng-model="user.nome" style="width:100px">
    <label>E-mail: </label><input type="text" required name="email" ng-model="user.email" style="width:100px">
    
    <input type="hidden" name="telefone" ng-model="user.telefone">
    <input type="hidden" name="cpf" ng-model="user.cpf">
    
    <input type="button" value="Adicionar" ng-click="addItem(user)" />
    <input type="submit" value="Enviar"/>
</form>
<br />

<div ng-repeat="item in items track by $index">
ID: {{item.soma}}<br />
Nome: {{item.nome}}<br />
E-mail: {{item.email}}<br /><br />
<!-- {{item.telefone}} - {{item.cpf}} -->
<!-- Trigger the modal with a button -->
<button type="button" class="btn btn-primary btn-xs" data-toggle="modal" data-target="#myModal" ng-click="addTributos(item)">Tributos</button>
<hr />
</div>

<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Tributos</h4>
      </div>
      <div class="modal-body">
        <label>Telefone: </label><input type="text" name="telefone" ng-model="produtoTrib.telefone">
        <label>CPF: </label><input type="text" name="cpf" ng-model="produtoTrib.cpf">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Atualizar</button>
      </div>
    </div>

  </div>
</div>
</body>
    
19.01.2017 / 02:57
1

You are already linking the two inputs to the model:

<label>Nome: </label><input type="text" ng-model="user.nome">
<label>E-mail: </label><input type="text" ng-model="user.email">

So, the following is unnecessary:

{nome: $("input[name='nome']").val()}

You can simply mention the template in the scope:

{nome: $scope.user.nome}

So test the model directly:

var temNome = !!$scope.user.nome;
    
13.01.2017 / 17:07