gpt4 book ai didi

javascript - 如何检查一个对象是否存在于数组中并在 AngularJS 中给它一个 ng 类

转载 作者:行者123 更新时间:2023-11-30 14:52:10 25 4
gpt4 key购买 nike

这里是傻瓜:https://plnkr.co/edit/SRjkoo2mi5C2P1dVsYST?p=preview

我一共有3个水果:

  $scope.fruits = [{
_id: "3",
name: "apple"
}, {
_id: "4",
name: "orange"
}, {
_id: "5",
name: "banana"
}];

并且有 2 家商店:

  $scope.shops = [{
name: "Tesco",
_id: "1",
fruits: [{
_id: "3",
name: "apple"
}]
},{
name: "Waitrose",
_id: "2",
fruits: [{
_id: "4",
name: "orange"
}]
}];

如您所见,每个商店只有 1 种水果。

在 View 中,我为每家商店展示了所有可用的水果,我想用红色突出显示那家商店中可用的水果(给出“class-1”类)。

我有以下内容,但它不起作用:

<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>

(灵感来自这个答案:How to check if something is in array from ng-class)

最佳答案

鉴于每个商店只有一种水果,语法应该是

 <div ng-class="shop.fruits[0].id.indexOf(fruit._id) === -1 ? 'class-1' : 'class-2'">{{fruit}}</div>

https://plnkr.co/edit/aTf0YClBXteXo01SOrBK?p=preview

更新了 plnkr https://plnkr.co/edit/cnzjGWSIT86Q2VYa6aSM?p=preview

html

 <div ng-repeat="fruit in fruits" ng-class="checkFruit(shop, fruit) ? 'class-1' : 'class-2'">{{fruit}}</div>

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;

}

或者你可以使用underscoreJS来写checkFruit函数算法

关于javascript - 如何检查一个对象是否存在于数组中并在 AngularJS 中给它一个 ng 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47948844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com