[javascript] How to check for an empty object in an AngularJS view

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?

This question is related to javascript angularjs

The answer is


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?


Try this:

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

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;
}

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)"

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"

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.


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 = {};


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)"

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>

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>

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 ;


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;

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>