0

I am trying to attach class dynamically in table's tr in Angular js like bellow :

ng-class="{
     'text-light' : inventory.newValue.disabled,
      'odd' : inventory.rowNumber % 2 === 1,
    {{inventory.first? 'loc-'unit.attachNumber : 'bldg-'inventory.parent.attachNumber }}

    }"

But it's not working,can anyone help me out how can I do this in AngularJs. Also I can't put this in controller.

Sandeep Tiwari
  • 2,042
  • 3
  • 24
  • 47
  • 1
    Does this answer your question? [AngularJS ngClass conditional](https://stackoverflow.com/questions/16529825/angularjs-ngclass-conditional) – BadPiggie Nov 07 '19 at 04:51
  • No I have gone through this topic doesn't cover dynamic class, means append some dynamic value in class – Sandeep Tiwari Nov 07 '19 at 07:22

2 Answers2

1

You forgot the string concatenation operator +:

'loc-'+unit.attachNumber
'bldg-'+inventory.parent.attachNumber

Furthermore the last member of you object is not valid. It is missing a key, we can only see a value.

You can try this:

ng-class="{
  'text-light' : inventory.newValue.disabled,
  'odd' : inventory.rowNumber % 2 === 1,
  'attachNumber' : inventory.first? 'loc-'+unit.attachNumber : 'bldg-'+inventory.parent.attachNumber }}
}"
Guillaume Adam
  • 191
  • 2
  • 10
0

if you use a lot of condition it is better write a function. in this way you will have a clear code and debuggable code.

like this in your controller

$scope.getRightClass = function(inventory, unit){
    var classes = [];

    if(inventory.newValue.disabled === true){
        classes.push('text-light');
    }

    if(inventory.rowNumber % 2 === 1){
        classes.push('odd');
    }

    if(inventory.first === true){
        classes.push('loc-' + unit.attachNumber)
    }else{
        classes.push('bldg-' + inventory.parent.attachNumber);
    }

    return classes.join(' ');
}

and this in your view

ng-class="getRightClass(inventory, unit)"
FarukT
  • 1,560
  • 11
  • 25