32

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?

Bob
  • 141
  • 1
  • 9
brabertaser19
  • 5,678
  • 16
  • 78
  • 184

15 Answers15

57

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)"
Md Hasan Ibrahim
  • 1,868
  • 19
  • 27
20

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>
Wallace Vizerra
  • 3,382
  • 2
  • 28
  • 29
8

Try this:

angular.equals({}, $scope.card)
Matteo Baldi
  • 5,613
  • 10
  • 39
  • 51
Yogesh Kate
  • 307
  • 3
  • 6
7

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)"
Jahongir Rahmonov
  • 13,083
  • 10
  • 47
  • 91
6

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;
Moncef Hassein-bey
  • 1,361
  • 9
  • 14
5

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?

Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
2

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

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"
pherris
  • 17,195
  • 8
  • 42
  • 58
  • This doesn't answer his question, this is an advice. Should be in the comment of his question, not posted as an answer. – bokkie Jan 14 '19 at 16:36
1

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 ;

Pravin P Patil
  • 169
  • 1
  • 5
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)"
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234
0

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>
Alexei - check Codidact
  • 22,016
  • 16
  • 145
  • 164
0

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

Eduardo Russo
  • 4,121
  • 2
  • 22
  • 38
  • 1
    Hi Priya! Welcome to Stack Overflow! If you edit your answer & explain why your code is cool, then it stands a better chance of receiving upvotes. Those will boost your reputation upwards! Here are some suggestions, which will help to make your answer better: 1. When creating answers, would you please add the proper capitalization & punctuation to your answers? 2. Could you edit the code example, to remove the extra white-spacing between attributes? 3. Adding links to external documentation or quotes from those sources are usually helpful too. Welcome to the SO community! :) – Clomp Mar 02 '18 at 07:41
0

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.

William Hou
  • 1,251
  • 14
  • 17
0

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>
Brian Sweat
  • 415
  • 2
  • 7
-1

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>
shriram
  • 14
  • 1