Search code examples
cssarraysangularjsng-classangularjs-ng-class

How do I make an ngClass reactive to array membership in Angular?


I'm trying to make a list class reactive to whether that list member's ID is in an array. I could handle that with a function in the controller, but that doesn't automatically update the class if the array changes.

Here is a plunker representing my problem, I want all the ids in $scope.redIds to be red. http://plnkr.co/edit/rl8WWgTRnksDkEddmhj9

Code below:

<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-ngController-production</title>


  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.min.js"></script>
  <script src="app.js"></script>

  <style>
    .red {
      background-color: red;
    }
  </style>


</head>
<body ng-app="controllerExample">
  <div ng-controller="controller">
    <!-- 1 and 4 should be red -->
    <div ng-repeat="id in ids">

      <span ng-class="id in redIds ? 'red' : ''">ID: {{id}}</span>
    </div>
  </div>
</body>
</html>

app.js:

(function(angular) {
angular.module('controllerExample', [])
  .controller('controller', ['$scope', controller]);

function controller($scope) {
  $scope.ids = [1,2,3,4];
  $scope.redIds = [1,4];
}
})(window.angular);

Thank you!

EDIT Plunker has been updated with working solution: http://plnkr.co/edit/rl8WWgTRnksDkEddmhj9


Solution

  • Basically you have wrong ng-class directive, it shouldn't be using id in redIds expression won't work, this kind of code only work with ng-repeat.

    For get this working you could use .indexOf here, which would check redIds array does contain the id element or not.

    Markup

    <div ng-repeat="id in ids">
       <span ng-class="{'red': redIds.indexOf(id) != -1}">ID: {{id}}</span>
    </div>
    

    Demo Plunkr