我正在使用ng-class来显示一个令人敬畏的字体真棒图标,但几个月后,ng-class使用的表达式难以维护并且难以尝试阅读:
<span ng-class="{'fa fa-close iconBlack':stain.StainStatus == 'Canceled', 'fa fa-exclamation-circle iconRed': stain.StainStatus == 'Missing', 'fa fa-clock-o iconOrange':stain.StainStatus == 'Ordered' || stain.StainStatus == 'Printed' || stain.StainStatus == 'In Process', 'fa fa-check iconGreen': stain.StainStatus == 'Verified' || stain.StainStatus == 'Completed', 'fa fa-pause iconPurple stainPauseIconFontSize': stain.StainStatus == 'On Hold', 'fa fa-ban iconRed':stain.Count > 1 && modifyModeActive}"></span>
一种解决方案是将每个图标放入自己的&lt; span&gt;然后根据需要在跨度上使用ng-show / hide,但我想知道还有哪些其他方法来维护像这样的大型ng-class表达式?
答案 0 :(得分:2)
ngClass
接受任何表达式,因此您可以将类定义对象放入控制器并用函数调用替换它:
<span ng-class="getMyClasses()"></span>
在您的控制器中:
$scope.getMyClasses = function() {
return {
'fa fa-close iconBlack':stain.StainStatus == 'Canceled',
'fa fa-exclamation-circle iconRed': stain.StainStatus == 'Missing',
'fa fa-clock-o iconOrange':stain.StainStatus == 'Ordered' || stain.StainStatus == 'Printed' || stain.StainStatus == 'In Process',
'fa fa-check iconGreen': stain.StainStatus == 'Verified' || stain.StainStatus == 'Completed',
'fa fa-pause iconPurple stainPauseIconFontSize': stain.StainStatus == 'On Hold',
'fa fa-ban iconRed':stain.Count > 1 && modifyModeActive
}
}
这可能会有一些性能问题,因为它必须在每个摘要调用上创建对象,因此您只需创建一次对象并仅返回其引用。然后在您知道它可能已更改时手动更新它。