此代码使用angularjs ng-table模块在表中显示值。
相关的html代码如下所示;
<div ng-controller="ViewCtrl" class="container">
<table ng-table="tableParams" class="table table-bordered">
<thead>
<tr>
<th>price_alert</th>
<th>lastPrice</th>
</tr>
<thead>
<tbody>
<tr ng-repeat="item in $data">
<td data-title="'price_alert'" ng-class="{ red: item.lastPrice < stk.price_alert }>
${{item.price_alert}}
</td>
<td data-title="'lastPrice'" ng-class="{ red: item.lastPrice < stk.price_alert }>
${{item.lastPrice}}
</td>
</tr>
</tbody>
</tbody>
</table>
</div>
CSS代码;
.red { color: red; }
控制器代码;
controller('ViewCtrl', ['$scope', '$http', 'moment', 'ngTableParams',
function ($scope, $http, $timeout, $window, $configuration, $moment, ngTableParams) {
var tableData = [];
//Table configuration
$scope.tableParams = new ngTableParams({
page: 1,
count: 100
},{
total:tableData.length,
//Returns the data for rendering
getData : function($defer,params){
var url = 'http://127.0.0.1/list';
$http.get(url).then(function(response) {
tableData = response.data;
$defer.resolve(tableData.slice((params.page() - 1) * params.count(), params.page() * params.count()));
params.total(tableData.length);
});
}
});
}])
在html代码中,此条件重复显示文本颜色ng-class="{ red: item.lastPrice < stk.price_alert
。如果可能的话,如何修改代码以保持DRY(不要重复自己)原则?
答案 0 :(得分:1)
听起来你只想消除一个额外的“红色”类声明。要做到这一点,将你的ng-class放在tr中:
<tr ng-repeat="item in $data" ng-class="{ red: item.lastPrice < stk.price_alert }">
<td data-title="'price_alert'">
${{item.price_alert}}
</td>
<td data-title="'lastPrice'">
${{item.lastPrice}}
</td>
</tr>
然后将你的css更改为:
.red td { color: red; }
你不能用这个css在这行中嵌套一个额外的表,但我猜你不需要。