florin florin - 1 year ago 64
AngularJS Question

Delegate method in expression in ng-class

I am trying to add a method to the expression of ng-class. I want to color a div based on some info found into a bounded object.

This is my view:

<div class="starter-template" ng-controller="MachineController as mc">
<div class="machineContainer" ng-repeat="machine in mc.data">
<div class="machineView" ng-class="{
'redDiv': mc.delegateCheckStatus(mc.STATES.down, machine.status),
'yellowDiv': mc.delegateCheckStatus(mc.STATES.idle, machine.status),
'greenDiv': mc.delegateCheckStatus(mc.STATES.running, machine.status)

This is my controller. Inside I have a method(delegateCheckStatus) that checks if i have mstatus in string machineStatus:

.controller('MachineController', ['MachineInfo','FormatName', function(MachineInfo,FormatName){
var vm = this;
vm.data = undefined;
vm.pattern = '^([a-zA-Z]+)([0-9]+)$';
vm.STATES = {
'idle': 'idle',
'down': 'down',
'running': 'running',
'notPosted': 'not posted'

var data = angular.fromJson(response.data);
vm.data = FormatName.formatName(data.machines);
}, function(response){

vm.delegateCheckStatus = function(mstatus, machineStatus){
var patt = new RegExp(mstatus);
return patt.test(val);
return false;
var theDataOfAllDatas = [
{ id: 1, name: "mnp111", ip: "", status: "down", description: "m1", errors: null },
{ id: 2, name: "mnp112", ip: "", status: "idle", description: "m2", errors: null },
{ id: 3, name: "mnp113", ip: "", status: "server running", description: "m3", errors: null }];

theDataOfAllDatas is my test array

Based on the value returned by the method delegateCheckStatus, I want to color the div( see the html file)

My css file looks like this:

.starter-template {
padding: 40px 15px;
float: left;
border: solid 1px;
border-radius: 3px;
padding: 2px;
background-color: #FF6666;
background-color: #FFFF66;
background-color: #66FF66;

My problem is that using the above, the divs are not colored. I did a little debug and I saw that the method delegateCheckStatus is called but no css is applied.

If I surround(in the html file) the expression with single quotes:

'redDiv': 'mc.delegateCheckStatus(mc.STATES.down, machine.status)'

then all the divs will be colored with the same color(in my case is the green color because this is the last color applied)

What is the proper way to add a method as expression in ng-class?

Thank you

Answer Source

The syntax you have in the snippet is correct:

ng-class="{'redDiv': mc.delegateCheckStatus(mc.STATES.down, machine.status), ...}

The problem seems to reside in the delegateCheckStatus function itself.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download