florin florin - 6 months ago 17
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)
}">{{machine.name}}</div>
</div>




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'
}


MachineInfo.getMachineInfo().then(function(response){
var data = angular.fromJson(response.data);
vm.data = FormatName.formatName(data.machines);
}, function(response){
console.log(response);
});

vm.delegateCheckStatus = function(mstatus, machineStatus){
var patt = new RegExp(mstatus);
if(patt.test(machineStatus)){
return patt.test(val);
}
return false;
}
}]);
var theDataOfAllDatas = [
{ id: 1, name: "mnp111", ip: "192.168.184.137", status: "down", description: "m1", errors: null },
{ id: 2, name: "mnp112", ip: "192.168.184.138", status: "idle", description: "m2", errors: null },
{ id: 3, name: "mnp113", ip: "192.168.184.139", 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;
}
.machineView{
float: left;
border: solid 1px;
border-radius: 3px;
padding: 2px;
}
.redDiv{
background-color: #FF6666;
}
.yellowDiv{
background-color: #FFFF66;
}
.greenDiv{
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

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.