1

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 ?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, I had already the correct logic. But your plunker really helped me understand how I should set my filter in my template.
-1

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

1 Comment

First statement is not correct. You can use custom filters to filter anything

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.