redAce
redAce

Reputation: 1798

Angular's filter to check if object is empty null or undefined

I would like to have a filter that will check if a given json object is empty, null or undefined. Without using any third-party lib.

function isObjValid(obj) {
      return !(obj === undefined || obj === null || Object.keys(obj).length === 0)
  };

But when I tried to filter the object from my template :

<ng-if ng-if="$ctrl.data | filter:isObjValid">
   ...
</ng-if>

I get this error :

Error: [filter:notarray] Expected array but received: {}

Is there any way to avoid notarray ?

Upvotes: 1

Views: 14730

Answers (2)

charlietfl
charlietfl

Reputation: 171679

Create a custom filter

angular.module('myApp').filter('isValidObject', function(){
    return function(obj){
      return !(obj === undefined || obj === null || Object.keys(obj).length === 0);
    }
});

Use in view:

<div ng-if="$ctrl.data | isValidObject">

DEMO

Upvotes: 3

Aravind
Aravind

Reputation: 41543

As per the Angular Documentation, you are allowed to use filters only for array of elements. In your case data seems to be just an object and not an array.

Suggesting you without a filter as in the below code

<body ng-controller="MainCtrl">
  <p>Hello {{name}}!</p>

  <div ng-if="isObjValid(data)">
    Valid data
  </div>
  <div ng-if="!isObjValid(data)">
    In Valid data
  </div>
  <div ng-if="isObjValid(name)">
    Valid name object
  </div>
</body>

Your controller must be the following

var app = angular.module('demoModule', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.isObjValid=function(obj) {
      return !(obj === undefined || obj === null || Object.keys(obj).length === 0)
  };
});

Check out the LIVE DEMO

Upvotes: -1

Related Questions