rick astley rick astley - 4 months ago 31
Javascript Question

multiple if checks in ng-class

So I have this piece of code in my angularjs app that I include in a table. I want to activate the class 'rare' if the index is 0, 1 or 2 only. The index is the rows. Let's say I have 8 rows in my table. Only the first 3 in it should have the class 'rare' applied to it.

ng-class="{rare : $index === 0, rare : $index === 1, rare : $index === 2}"

But is there an easier/shorter way of writing it?
Is this good practice? I dont think it looks very good, even though it works.
How would you write the if checks?

I tried:

ng-class="{rare : $index === {0,1,2}}
but it didn't work


You could do something like this, if you have an list of values.

var app = angular.module("sampleApp", []);

app.controller("sampleController", ["$scope",
  function($scope) {
    $scope.data = "Test";
    $scope.val1 = 2;
    $scope.val2 = 5;
.active {
  color: red;
.not-active {
  color: blue;
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.8/angular.min.js"></script>
<div ng-app="sampleApp">
  <div ng-controller="sampleController">
    <div ng-class="[1,2,3].includes(val1)? 'active' : 'not-active'">{{data}}</div>
    <div ng-class="[1,2,3].includes(val2)? 'active' : 'not-active'">{{data}}</div>