[英]How to check if an object exists in an array and give it an ng-class in AngularJS
Plunker here: https://plnkr.co/edit/SRjkoo2mi5C2P1dVsYST?p=preview 在这里暴跌: https ://plnkr.co/edit/SRjkoo2mi5C2P1dVsYST ? p = preview
I have 3 fruits in total: 我总共有3种水果:
$scope.fruits = [{
_id: "3",
name: "apple"
}, {
_id: "4",
name: "orange"
}, {
_id: "5",
name: "banana"
}];
and there are 2 shops: 并且有2家商店:
$scope.shops = [{
name: "Tesco",
_id: "1",
fruits: [{
_id: "3",
name: "apple"
}]
},{
name: "Waitrose",
_id: "2",
fruits: [{
_id: "4",
name: "orange"
}]
}];
Each shop only has 1 fruit available as you can see. 如您所见,每个商店只有1个水果。
In the view, I'm showing for each shop, all the fruits available in total and I want to highlight in red, only the fruits that are available in that shop (giving the "class-1" class). 在该视图中,我正在为每个商店显示总计可用的所有水果,并且我要用红色突出显示,仅显示该商店中可用的水果(给予“ class-1”类)。
I have the following, but it's not working: 我有以下内容,但无法正常工作:
<div ng-repeat="shop in shops">
<div>{{shop.name}}</div>
<div ng-repeat="fruit in fruits" ng-class="shop.fruits.indexOf(fruit._id) !== -1 ? 'class-1' : 'class-2'">{{fruit}}</div>
</div>
(Inspiration taken from this answer: How to check if something is in array from ng-class ) (此答案的启示: 如何检查ng-class数组中是否包含某些内容 )
given that each shop only has one fruit, the syntax should be 假设每个商店只有一个水果,语法应为
<div ng-class="shop.fruits[0].id.indexOf(fruit._id) === -1 ? 'class-1' : 'class-2'">{{fruit}}</div>
https://plnkr.co/edit/aTf0YClBXteXo01SOrBK?p=preview https://plnkr.co/edit/aTf0YClBXteXo01SOrBK?p=preview
updated plnkr https://plnkr.co/edit/cnzjGWSIT86Q2VYa6aSM?p=preview 更新的plnkr https://plnkr.co/edit/cnzjGWSIT86Q2VYa6aSM?p=preview
html HTML
<div ng-repeat="fruit in fruits" ng-class="checkFruit(shop, fruit) ? 'class-1' : 'class-2'">{{fruit}}</div>
js JS
$scope.checkFruit = function(shop, oneFruit) {
for(var i = 0, m = shop.fruits.length; i < m; i++) {
if(shop.fruits[i]._id === oneFruit._id) {
return true;
}
}
return false;
}
or you can use underscoreJS to write the checkFruit function algorithm 或者您可以使用underscoreJS编写checkFruit函数算法
我不熟悉Angular,但有可能做到这一点吗?
<div ng-class="shop.fruits.find(sf => sf._id === fruit._id) ? 'class-1' : 'class-2'">{{fruit}}</div>
In your case you can easily add specific class name for each div related to shop. 根据您的情况,您可以轻松地为与商店相关的每个div添加特定的类名称。 Therefore you can add few lines of css:
因此,您可以添加几行css:
.shop-1 .fruit-item {background: red;}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.