我有以下元素。
<div> My element</div>
和以下对象:
$scope.myObject = {'life_log' : [{status: 'ALIVE'},{status: 'DEAD'}]}
如果所有状态都为ALIVE,我该如何显示元素。
我知道如何在变量上使用ng-show但是这样的条件呢?
答案 0 :(得分:2)
您必须创建一个循环遍历数组的函数,并检查所有状态是否为“ALIVE”。或者只在阵列上使用reduce方法:
$scope.allStatusesAreAlive = $scope.myObject.life_log.reduce(function(a, b) {
if (a === false) return false;
if (b.status === 'DEAD') return false;
return true;
}, true);
然后,如果$ scope.allStatusesAreAlive为true,则可以显示元素:
<div ng-if="allStatusesAreAlive"> My element</div>
答案 1 :(得分:1)
你可以做这样的事情
angular.forEach($scope.myObject.life_log, function(item){
if(item.status !=='ALIVE'){
$scope.isAlive = false;
break;
}else{
$scope.isAlive = true;
}
});
然后在你的HTML中
<div data-ng-if="isAlive">My element</div>
答案 2 :(得分:0)
检查以下链接
https://plnkr.co/edit/ermeKk1dBX8D54pL7vHQ?p=preview
角度代码:
$scope.myObject = {'life_log' : [{status: 'ALIVE'},{status: 'DEAD'}]}
$scope.val=true;
for(i=0;i<$scope.myObject.life_log.length;i++){
if($scope.myObject.life_log[i].status != "ALIVE")
$scope.val=false;
}
html代码:
<div ng-show="val">My element</div>
答案 3 :(得分:-1)
// This is here to make it configurable
$scope.keys = Object.keys($scope.myObject);
// In this case you have the "life_log" key
$scope.keys.forEach(k => {
$scope.myObject[k].forEach((d) => {
// our object here is myObject["life_log"];
// obj is a temp array to check the amount of statuses that are dead
var obj = [];
d["allAlive"] = d.status.forEach( s =>{
if(s == 'DEAD'){
obj.push("Dead");
}
});
if(obj.length > 0){
d.allAlive = false
}else{
d.allAlive = true;
}
});
});
<div ng-if="myObject[o].allAlive>
ALL ALIVE
</div>