4

I want to hide a div if no object within a array has a specific property set to false.

The property looks like this:

$scope.myObjArray = [
    {"Id":"1","IsBuiltIn":true},
    {"Id":"2","IsBuiltIn":true}
];

I want to hide my div if there is no object within myObjArray that has IsBuiltIn set to false. So the above array should hide the div. The following should show it (because at least one object has IsBuiltInset to false):

$scope.myObjArray = [
    {"Id":"1","IsBuiltIn":true},
    {"Id":"2","IsBuiltIn":true},
    {"Id":"3","IsBuiltIn":false}
];

I tried to solve this using a ForEach without success:

<div ng-show="myObjArray.ForEach(e, function(){e.IsBuiltIn})">
    Hello, World!
</div>

Here is my plnkr.

1
  • 1
    Place your logic into a scope function that returns a true or false. It's not working cause you are using an array ForEach. Too lazy to code. xD Commented Jun 2, 2016 at 9:28

1 Answer 1

6

In Controller, create a function to check if any of the object in the array has false value for the property IsBuiltIn using Array#some

$scope.containsFalsy = (arr) => arr.some(o => o.IsBuiltIn === false);

This is using ES6 arrow function syntax. The above function is equivalent to

$scope.containsFalsy = function (arr) {
    return arr.some(function (obj) {
        return obj.IsBuiltIn === false;
    });
};

Call the function from the View

<div ng-hide="containsFalsy(myObjArray)">

Plunker Demo

var app = angular.module('myApp', []);

app.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
  $scope.myObjArray = [{
    "Id": "1",
    "IsBuiltIn": true
  }, {
    "Id": "2",
    "IsBuiltIn": true
  }];

  $scope.myObjArray1 = [{
    "Id": "1",
    "IsBuiltIn": true
  }, {
    "Id": "2",
    "IsBuiltIn": true
  }, {
    "Id": "3",
    "IsBuiltIn": false
  }];

  $scope.containsFalsy = (arr) => arr.some(o => o.IsBuiltIn === false);
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myApp">
  <div ng-controller="MainCtrl">
    <div ng-hide="containsFalsy(myObjArray)">
      Hello, World!
    </div>


    <div ng-hide="containsFalsy(myObjArray1)">
      Can you see me?
    </div>
  </div>
</div>

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Tushar, looks solid :-). Is there no way to check this within the ng-hide directive (without a controller function?)
No @jisaak tushar's right, you need the controller function to do it for you - don't pollute templates with lots of logic.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.