简体   繁体   中英

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

I have 3 fruits in total:

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

and there are 2 shops:

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

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

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 )

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

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

}

or you can use underscoreJS to write the checkFruit function algorithm

我不熟悉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. Therefore you can add few lines of css:

.shop-1 .fruit-item {background: red;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM