Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if an object is an empty object in a AngularJS template

Tags:

I have a simple object in a controller which can sometimes be empty ({}).

app.controller('TestController', function() {   var vm = this;    vm.testObject = {}; }); 

I want to hide or show some DOM-elements in the corresponding template when the object is empty or not.

I tried to do it with a simple <div ng-if="vm.testObject"> but when vm.testObject === {} it is considered true in the ng-if.

<div ng-controller="TestController as vm">   <div ng-if="vm.testObject">     Test Object is not empty   </div>   <div ng-if="!vm.testObject">     Test Object is empty   </div> </div> 

Is there a simple way to check for an empty object in the template? Preferably without adding new variables to the scope.

Here is a working Plunker: http://plnkr.co/edit/Qed2MKmuedcktGGqUNi0?p=preview

like image 469
DanEEStar Avatar asked May 21 '15 07:05

DanEEStar


People also ask

How to Check if an object is empty in JS?

Use Object. Object. keys will return an array, which contains the property names of the object. If the length of the array is 0 , then we know that the object is empty. We can also check this using Object.

How can we say whether an object is an empty object or not angular 6?

return Object.keys(obj).length === 0 ; This is typically the easiest way to determine if an object is empty.


2 Answers

You should use an AngularJs filter:

Javascript:

app.filter('isEmpty', [function() {   return function(object) {     return angular.equals({}, object);   } }]) 

Html template:

<div ng-if="!(vm.testObject | isEmpty)">   Test Object is not empty </div> <div ng-if="vm.testObject | isEmpty">   Test Object is empty </div> 

Updated plunkr: http://plnkr.co/edit/J6H8VzUKnsNv1vSsRLfB?p=preview

like image 81
Numyx Avatar answered Oct 09 '22 13:10

Numyx


Are you ok with moving the equality check to the ng-if?

<div ng-controller="TestController as vm">   <div ng-if="!equals({}, vm.testObject)">     Test Object is not empty   </div>   <div ng-if="equals({}, vm.testObject)">     Test Object is empty   </div> </div> 

Otherwise, provide a helper on the scope

app.controller('TestController', function() {   var vm = this;    vm.testObject = {};    vm.empty = function() {       return vm.testObject === {};   }; }); 

then

<div ng-controller="TestController as vm">   <div ng-if="!vm.empty()">     Test Object is not empty   </div>   <div ng-if="vm.empty()">     Test Object is empty   </div> </div> 
like image 26
kaveman Avatar answered Oct 09 '22 13:10

kaveman