How to check for an empty object in an AngularJS view

All we need is an easy explanation of the problem, so here it is.

In the controller’s scope I have something like:

$scope.card = {};

In the view I must check if my object is still an empty literal, {}, or if it contains some data in some fields.

I tried this:

ng-show="angular.equals({}, card)"

and

ng-show="!angular.equals({}, card)"

but it didn’t work.

Are there any better ways? How do you check if an object is empty or if it contains some fields?

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

You can use: Object.keys(card).length === 0

But make sure you use it from a method of the controller as the Object is not available in the view, like:

$scope.isObjectEmpty = function(card){
   return Object.keys(card).length === 0;
}

Then you can call the function from the view:

ng-show="!isObjectEmpty(card)"

Method 2

Use json filter and compare with '{}' string.

<div>
    My object is {{ (myObject | json) == '{}' ? 'Empty' : 'Not Empty' }}
</div>

ng-show example:

<div ng-show="(myObject | json) != '{}'"></div>

Method 3

Try this:

angular.equals({}, $scope.card)

Method 4

Create a function that checks whether the object is empty:

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

Then, you can check like so in your html:

ng-show="!isEmpty(card)"

Method 5

http://plnkr.co/edit/u3xZFRKYCUh4D6hGzERw?p=preview

Because angular is not available from the scope, you can pass it to your controller scope.

$scope.angular = angular;

Method 6

please try this way with filter

angular.module('myApp')
    .filter('isEmpty', function () {
        var bar;
        return function (obj) {
            for (bar in obj) {
                if (obj.hasOwnProperty(bar)) {
                    return false;
                }
            }
            return true;
        };
    });

usage:

 <p ng-hide="items | isEmpty">Some Content</p>

Via from : Checking if object is empty, works with ng-show but not from controller?

Method 7

This will do the object empty checking:

<div ng-if="isEmpty(card)">Object Empty!</div>


$scope.isEmpty = function(obj){
  return Object.keys(obj).length == 0;
}

Method 8

You should not initialize your variable to an empty object, but let it be undefined or null until the conditions exist where it should have a non-null/undefined value:

$scope.card;

if (someCondition = true) {
    $scope.card = {};
}

Then your template:

ng-show="card"

Method 9

You can use plain javascript Object class to achieve it,
Object class has keys function which takes 1 argument as input as follows,

Object.keys(obj).length === 0

You can achieve it in 3 ways,
1) Current controller scope
2) Filter
3) $rootScope

1) First way is current controller scope,

$scope.isObjEmpty = function(obj){
return Object.keys(obj).length === 0; }

Then you can call the function from the view:

ng-show=”!isObjEmpty(obj)” if you want to show and hide dom dynamically &
ng-if=”!isObjEmpty(obj)” if you want to remove or add dom dynamically.

2) The second way is a custom filter. Following code should work for the object & Array,

angular.module('angularApp')
    .filter('isEmpty', [function () {
        return function (obj) {
            if (obj == undefined || obj == null || obj == '')
                return true;
            if (angular.isObject(obj))
                return Object.keys(obj).length != 0;

            for (var key in obj) {
                if (obj.hasOwnProperty(key)) {
                    return false;
                }
            }
            return true;
        };
    }]);

    <div ng-hide="items | isEmpty"> Your content's goes here </div>

3) The third way is $rootScope,
create a plain javascript function and add it in $rootScope server it will accessible default in all scopes and UI.

function isObjEmpty (obj){
return Object.keys(obj).length === 0; }

$rootScope.isObjEmpty = isObjEmpty ;

Method 10

Create a $scope function that check it and returns true or false, like a “isEmpty” function and use in your view on ng-if statement like

ng-if="isEmpty(object)"

Method 11

I have met a similar problem when checking emptiness in a component. In this case, the controller must define a method that actually performs the test and the view uses it:

function FormNumericFieldController(/*$scope, $element, $attrs*/ ) {
    var ctrl = this;

    ctrl.isEmptyObject = function(object) {
        return angular.equals(object, {});
    }
}

<!-- any validation error will trigger an error highlight -->
<span ng-class="{'has-error': !$ctrl.isEmptyObject($ctrl.formFieldErrorRef) }">
    <!-- validated control here -->
</span>

Method 12

I had to validate an empty object check as below

ex:

<div  data-ng-include="'/xx/xx/xx/regtabs.html'" data-ng-if =
    "$parent.$eval((errors | json) != '{}')" >
</div>

The error is my scope object, it is being defined in my controller as $scope.error = {};

Method 13

A good and effective way is to use a “json pipe” like the following in your HTML file:

   <pre>{{ yourObject | json }}</pre>

which allows you to see clearly if the object is empty or not.

I tried quite a few ways that are showed here, but none of them worked.

Method 14

If you plan on using a lot of the methods and properties of Object in your Angular JS app, why not use:

angular.module('core').run(function ($rootScope) {
     $rootScope.Object = window.Object;
});

Then in your view, you could do something like:

<div ng-if="Object.keys(fooBar).length > 0"></div>

Method 15

You have to just check that the object is null or not. AngularJs provide inbuilt directive ng-if. An example is given below.

<tr ng-repeat="key in object" ng-if="object != 'null'" >
    <td>{{object.key}}</td>
    <td>{{object.key}}</td>
</tr>

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply