Search code examples
angularjsng-class

ng-class isnt work well, not validate a expression


My problem is that my project is not validating ng-class well, even when starting apply a class that should not

var app = angular.module('plunker', ['angular.filter']);

app.controller('MainCtrl', function($scope) {
  $scope.colores = [{
    "name": "red"
  }, {
    "name": "blue"
  }, {
    "name": "pink"
  }, {
    "name": "green"
  }, {
    "name": "orange"
  }];
  
  $scope.color = [];
  
  $scope.setColors = function(x){
    if(x == 1){
      $scope.color = ['red', 'blue', 'orange'];
    }else{
      $scope.color = ['green', 'pink'];
    }
    
    console.log($scope.color);
  }
  
  $scope.changeColor = function(pColor){
    return $.inArray(pColor, $scope.color);
  };
  
});
/* Put your css in here */

.red{background: red;}
<!DOCTYPE html>
<html ng-app="plunker">

<head>
  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>
  <script>
    document.write('<base href="' + document.location + '" />');
  </script>
  <link rel="stylesheet" href="style.css" />
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
  <script data-require="angular.js@1.5.x" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.js" data-semver="1.5.11"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.16/angular-filter.js"></script>
  <script src="app.js"></script>
</head>

<body ng-controller="MainCtrl">
  
<select ng-model="x">
  <option value="0">0</option>
  <option value="1">1</option>
</select>
<button ng-click="setColors(x)">Change</button>
  

<div ng-repeat="color in colores | filter: { category: subcategory.category, subcategory: subcategory.subcategory }"><!--Level 3-->
  <p ng-class="{ 'red': changeColor( '{{ color.name }}' ) }" class=''>{{ color.name }}</p>
</div>


</body>

</html>

What I need is that every time my array changes, the p tag activates or deactivates the red class if the name of this label p is found inside the array.

I have been looking for a solution in other questions but none has solved the problem.

I attach the project


Solution

  • ng-class needs a boolean expression:

    E.g.

    ng-class="{ 'red': color=='red' }"
    

    In your example $scope.changeColor return -1