Total Pageviews

2015/09/10

[AngularJS] How to set CSS style conditionally

Requirement
We use ng-repeat directive instantiates a template once per item from a collection
Here is the code snippet:
1
2
3
4
5
6
7
<tbody data-ng-repeat="fms406v3 in fms406v3List" data-ng-form="formInTableRow" data-c-form-validation>
 <tr>
       <td class="text-left border-right"><span data-ng-bind="fms406v3.pdateWithDesc"></span></td>
       <td class="text-center border-right"><span data-ng-bind="fms406v3.rocWeekDate"></span></td>
    <!-- ignore .... -->
 </tr>
</tbody> 

Our requirement is to set each row's background color depends on the date is workday or weekend. If the date is workday, then set its background color to white. If the date is weekend, then set its background color to yellow.

How-To
Apply ngStyle directive set CSS style on an HTML element conditionally.

Here is the code snippet for JavaScript:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
//set row style: 假日底色顯示黃色;工作日底色顯示白色 
// 非工作日註記 (1: 休假日, 0: 工作日)
$scope.setRowStyle = function(noWorkInd){
    var rowStyle = null;
    if(noWorkInd == 0){ //工作日
        rowStyle = {'background-color' : 'white'};
    }else if(noWorkInd == 1){ //休假日
        rowStyle = {'background-color' : 'yellow'};
    }
    return rowStyle;
};

Here is the code snippet for HTML:

1
2
3
4
5
6
7
<tbody data-ng-repeat="fms406v3 in fms406v3List" data-ng-form="formInTableRow" data-c-form-validation>
  <tr data-ng-style="setRowStyle(fms406v3.noWorkInd)"  >
       <td class="text-left border-right"><span data-ng-bind="fms406v3.pdateWithDesc"></span></td>
       <td class="text-center border-right"><span data-ng-bind="fms406v3.rocWeekDate"></span></td>
    <!-- ignore .... -->
  </tr>
</tbody> 

Test :


REFERENCES
[1] https://docs.angularjs.org/api/ng/directive/ngStyle

No comments: