Reputation: 775
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
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
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