How to verify, for each item inserted in $Scope.items[], whether fields have been filled in

Asked

Viewed 164 times

1

How to verify, for each item inserted in $Scope.items[], if Telephone and CPF were completed?

Intended scenario:

The user must enter at least 1 item, if negative, when clicking "Send" displays an "Alert"[ALREADY IMPLEMENTED]

By clicking "Submit" and the user did not fill in the fields Telephone and CPF, for each inserted item, an "Alert" should be displayed. [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>
<script src="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>


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

  • is something I’ve been seeing in your angular codes, if you’re mixing jQuery with Angular needlessly, you should review that for your future codes. a council...

  • Yes, I have science. Thanks for the advice, I’m looking to review this, however this line nome: $("input[name='nome']").val(), in another code (http://answall.com/q/172553/31236) did not work nome: $scope.nome or nome: user.nome. @Virgilionovic, I even mentioned you in the answer: http://answall.com/a/173311/31236

  • Maybe because you couldn’t find a quick way to solve the problem, I believe it was not belonging to the controller and the application, is something... but, without seeing it gets complicated. That screen I remember well, I did my best to help, but, without seeing the code where it is running we end up not knowing what is programmed, it is very complicated and I understand you ...!!!

  • 1

    Thanks for the layout! I will be reviewing what happened, really was a "gambiarra" for the quick need to solve the problem.

2 answers

1

You’re 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">

Therefore, the section below is unnecessary:

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

You can simply mention the model in the scope:

{nome: $scope.user.nome}

Thus, test the model directly:

var temNome = !!$scope.user.nome;
  • Hello @Onosendai, could you see the edition I made? [Desired scenario]

1


Add a function to validate the fields before running the 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 = '';
    }               
};

Assign a name to the widget form will facilitate the use of the validation of Angularjs itself, in this example I used the myForm and includes the novalidate not to execute HTML5 validation.

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

Angularjs validation uses the attribute required HTML5 to specify that the field must be completed:

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">

Afterward:

<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 itself input[type=hidden] and change the name of the elements input[name=email] in order 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">

Afterward:

<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 missing CPF or Phone, runs the for and go 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;
     }
   }

}

Upshot:

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>
<script src="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>

  • Carlos, exactly what you needed! The reward will be free in 4 hours. @Carlosfernandes

Browser other questions tagged

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