Check empty object AngularJS

2

I have some fields where I pass some filters for a query in the database. I would like to check if the object is empty, so the query would not be performed.

I tried this way:

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
           return false;
    }
    return true;
}

I pass the object this way:

$scope.filtrarContratos = function(contrato) {
      if(isEmpty(contrato)){
         console.log("Inválido");
      }
}

But the result is always false .

This is the result I have in the console when I make an object console:

Object { contrato: "" }

I've tried an if to check if it was equal to "" but it did not work either.

    
asked by anonymous 28.12.2015 / 17:59

2 answers

0

I solved the problem by checking the attributes of the object instead of the whole object.

Ex:

$scope.filtrarContratos = function(contrato) {
    if (isEmpty(contrato.contrato) && isEmpty(contrato.contratante) && isEmpty(contrato.codigoAgrupador)) {
        console.log("Inválido");
    }
}

Function that checks if it is empty:

function isEmpty(obj) {
    for(var prop in obj) {
      if(obj.hasOwnProperty(prop))
      return false;
    }

    return true;
  }

Html:

<div class="row">
   <div class="col-md-3">
      <input class="form-control" type="text" ng-model="contrato.contrato" placeholder="Contrato"/>
   </div>
   <div class="col-md-3">
      <input class="form-control" type="text" ng-model="contrato.contratante" placeholder="Contratante"/>
   </div>
   <div class="col-md-3">
      <input class="form-control" type="text" ng-model="contrato.codigoAgrupador" placeholder="Cod. Agrupador"/>
   </div>
   <div class="col-md-3">
      <button class="btn btn-primary btn-block" ng-click="filtrarContratos(contrato)">
      <i class="fa fa-search"></i>
      Filtrar
      </button>
   </div>
</div>

Example working: link

    
28.12.2015 / 18:14
4

Fixed function, it worked here

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop) && obj.prop != "" && obj.prop != undefined)
           return false;
    }
    return true;
}
    
28.12.2015 / 18:08