samu101108
samu101108

Reputation: 775

Rectifying a controller for not adding empty values

I'm tryng out a CRUD with AngularJS (Project) and I saw that when I press 'Cadastrar' button, it keeps pushing into the array even if it is empty. What I want is to prevent this behavior to occur.

      $scope.add = function(){
      $scope.listProducts.push(
  {
    codigo:$scope.codigo, nome:$scope.nome, email:$scope.email, login:$scope.login
  });
    $scope.codigo = '';
    $scope.nome = '';
    $scope.email = '';
    $scope.login = '';
    };

what should be a good thing to do?

Upvotes: 0

Views: 23

Answers (2)

Anil Kumar
Anil Kumar

Reputation: 100

Your $scope.codigo is undefined when pushing to the array. If you want to prevent it push into array.

You have to use condition like angular.isDefined($scope.codigo) and it condition satisfies then only it push the data into array.

You can calculate $scope.codigo depends opon the number of items present in your list.

if( angular.isDefined($scope.codigo)){
$scope.listProducts.push(
  {
    codigo:$scope.codigo, nome:$scope.nome, email:$scope.email, login:$scope.login
  });
    $scope.codigo = '';
    $scope.nome = '';
    $scope.email = '';
    $scope.login = '';
    };
}

Upvotes: 1

developer033
developer033

Reputation: 24894

In a short way, you should test the properties that are required before push.

Ex:

if ($scope.codigo && $scope.nome && $scope.email && $scope.login) {
  $scope.listProducts.push({
    codigo: $scope.codigo, 
    nome: $scope.nome, 
    email: $scope.email, 
    login: $scope.login
  });
}

Upvotes: 1

Related Questions