Reputation: 58991
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 IsBuiltIn
set 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.
Upvotes: 4
Views: 3187
Reputation: 87203
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)">
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>
Upvotes: 6