Search code examples
htmlangularjsangularjs-ng-repeatng-class

Add ng-class with expression false


Hi I got a object with a list within I would like loop in my html with a ng-repeat. The list is key-value and the value is true or false. In my html I have a div with a class and a own background-color. So when I do the ng-repeat, I would like to check, if the value in the list is false and add a new class with a new background-color. I used for this ng-class with an expression, but it does'nt work. This is my object:

$scope.list = [
    {
        "Name" : "Jacob",
        "Properties" : {
               "P1": true,
               "P2": true,
               "P3": false
        }
    },
    {
        "Name" : "James",
        "Properties" : {
               "P1" : false,
               "P2" : true,
               "P3" : true
        }
    },
    {
        "Name" : "Hector",
        "Properties" : {
               "P1" : false,
               "P2" : false,
               "P3" : true
        }
    }
]

Then I got follow html:

<div ng-repeat="item in list">
    <div class="myContainer">
        <div class="cMyBox cColor1" ng-class="{cWhite: !item.Properties.P1}"></div>
        <div class="cMyBox cColor2" ng-class="{cWhite: !item.Properties.P2}"></div>
        <div class="cMyBox cColor3" ng-class="{cWhite: !item.Properties.P3}"></div>
    </div>
</div>

And this is my css:

.myContainer {display: flex; flex-direction: row;}
.cMyBox {width: 20px; height: 20px; background-color: blue;}
.cWhite{background-color: white;}
.cColor1 {background-color: red;}
.cColor2 {background-color: blue;}
.cColor3 {background-color: green;}

And the moment it does'nt change the color, when it's false. I also tried with ng-class="{cWhite: item.Properties.P1 == false}".

I used this way to add a class with ng-class + expression a few times, but now it does'nt work. Maybe my repeat or my list is wrong.

Thanks!


Solution

  • This is the problem with the order in which the css class is defined. Put your .cWhite{background-color: white;} to the last. because cWhite and cColor1,cColor2,cColor3 are in the same scope level, the browser will take the first one and leave the rest of the backgroud-color value. I believe this should solve your problem

    .myContainer {display: flex; flex-direction: row;}
    .cMyBox {width: 20px; height: 20px; background-color: blue;}
    .cColor1 {background-color: red;}
    .cColor2 {background-color: blue;}
    .cColor3 {background-color: green;}
    .cWhite{background-color: white;}