Search code examples
angularjsng-classangular1.6

Angular.js (1.6.9) conditonally apply class using $eval


I am trying to use ng-class to apply conditional formatting within an ng-repeat. The condition should be based on evaluation of an object data string.

I am trying to get his code to apply bold to the 3rd item. I have done my best at trying $eval or $parse to no avail.

  <body ng-app="examsApp">
    <div ng-controller="ExamsController as examsList">
      <div ng-repeat="exam in examsList.exams">
        <span ng-repeat="levelnum in exam.levels.levelnums" ng-class="{ 'bold': $eval(exam.levels.evalby[$index]) }">
          {{levelnum}}
        </span>
      </div>
    </div>
  </body>


var data = [
    {
        "id": "exam1",
        "text": "Exam 1",
        "levels":
            {
                "levelnums": ['2', '3', '4', '5'],
                "evalby": ['$scope.bold === 0', '$scope.bold ==== 1', '$scope.bold === 2', '$scope.bold === 3']
            }
    }
]

angular.module('examsApp', [])
    .controller('ExamsController', ['$scope', function ($scope) {
        var examsList = this;
        examsList.exams = data;

        $scope.bold = 2;
}])

Plunkr


Solution

  • Your plunk has a handful of small issues, two of which can be found by opening the developer console:

    1. You're not including angularJS.
    2. You are trying to ng-repeat over examsList.exams outside of the div that is assigned the examList controller.
    3. You have an extra ')' at the end of your last value in the eval array.
    4. All of your rules in the eval array currently resolve to false.
    5. You don't have a css rule for the bold class defined.

    Plunkr