mindparse mindparse - 5 months ago 28
AngularJS Question

Passing in element properties to ng-class expressions

I was wondering if it's possible to use

ng-class
and supply an expression that's based on the inner content of the element it's being used on.

So for example, say I have:

<table>
<tr ng-repeat="result in results">
<td ng-class="vm.getNumberClass(...)">
{{vm.getSomeMagicNumber(result)}}
</td>
</tr>
</table>


Could I pass in the value of the
td
cell content as an argument to the
getNumberClass
function I am using as an expression on the
ng-class
directive?

EDIT

When I say pass in the value of the td cell content, I mean pass in the evaluated result of
{{vm.getSomeMagicNumber(result)}}
as an argument

I could do something like.

<td ng-class="vm.getNumberClass(vm.getSomeMagicNumber(result))">
{{vm.getSomeMagicNumber(result)}}
</td>


Whilst this does work for my scenario, it feels like a performance hit as its calling the function twice

Answer

I don't really understand what you are willing to do inside these functions.

Here is what I'd do to avoid calling the function twice, you'll have to store the result somewhere (If it's not on the CPU, it has to be on the RAM):

angular.module('myApp', []);

angular.module('myApp').controller('MyCtrl', function() {
  var vm = this;

  vm.getNumberClass = function(number) {
    var className = '';

    switch (parseInt(number)) {
      case 3:
        className = 'red';
        break;
      case 6:
        className = 'coral';
        break;
      case 9:
        className = 'pink';
        break;
    }
    
    return className;
  };

  vm.getSomeMagicNumber = function(result) {
    // Any process here and store the result for each row
    result.magicNumber = result.id * 3;
    
    return result.magicNumber;
  };

  vm.results = [{
    id: '1'
  }, {
    id: '2'
  }, {
    id: '3'
  }];
});
.red {
  background-color: red;
}

.coral {
  background-color: coral;
}

.pink {
  background-color: pink;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl as vm">
  <table>
    <tr ng-repeat="result in vm.results">
      <td ng-class="vm.getNumberClass(result.magicNumber)">
        {{vm.getSomeMagicNumber(result)}}
      </td>
    </tr>
  </table>
</div>