How to hide element if object in array is missing field

by oderfla   Last Updated September 11, 2019 19:26 PM - source

So I have an html element like this:

 <div ng-hide="!myarr.length">
    Im showing
 </div>

Somewhere else an array is populated.
Before it is being populated it will not have a length, so the div above will not show up.

However, when the array will be filled with data (json objects) I need to understand if all the objects in the array contain a specific field (and it cannot be empty).

So my json could eventually look like this:

myarr[0] = {name: 'jack', type: ''}
myarr[1] = {name: 'jack'}
myarr[2] = {name: 'jack', type: 'mytype'}

In the case above, the div should continue to be hiding as not all the json objects contain a "type"-field that is not empty.

How do I accomplish this? I was thinking to have an OR statement in the ng-hide. Maybe I could use the "some"-function. But when doing this it seems I cannot run this kind of function inside the ng-hide (at least my editor marks the code with red). Is there an alterntive way to do this without needing to call a function in my controller?

Tags : angularjs


Answers 2


You can add a watch to the Array and run a loop when it changes to check for "type" and if there is an element where type is null set a hide parameter to false.

Something along the lines of this;

Controller

vm.scope.$watch('myarr', function(), true {
  vm.hideMe = false;
  for (var i = 0; i < myarr.length; i++) {
    if (myarr[i].type == null) {
      vm.hideMe = true;
    }    
  }    
});

Html

<div ng-hide="hideMe">
    Im showing
 </div>
JayDee
JayDee
September 11, 2019 15:15 PM

When you retrieve the data, you can iterate over each object in the array and examine the individual objects. If any individual object DOES NOT contain the necessary data, set the display flag to false and break out of the loop.

$scope.showElement = true;
$scope.array = [
    {name: 'jack', type: ''},
    {name: 'jack'}
    {name: 'jack', type: 'mytype'}
];

for(let i=0; i<$scope.array.length; i++){
  if($scope.array[i].type === undefined || $scope.array[i].type === ''){
    $scope.showElement = false;
    break;
  }
}
CoGaMa64
CoGaMa64
September 11, 2019 19:25 PM

Related Questions





Filters in Angular Js

Updated April 20, 2015 04:11 AM

Angular filter and limitTo not working as expected

Updated August 04, 2016 08:12 AM