我有以下代码,它是一个 ionic 列表,用于填充检索到的数据。我尝试根据状态响应将其颜色编码为不同的颜色。
<ion-list>
<ion-item ng-repeat="test in tests" class ="item-text-wrap" style="height:40%">
<a href="#/tab/test/test-detail/{{test.ID}}">
<div style="width:80%; float:left;">
<table>
<span ng-if="test.Status == 'Cleared'" ng-style="color:green">
<tr>
<td> <strong>Remark: </strong></td>
<td style="padding:3px">{{test.Remark}}</td>
</tr>
<tr>
<td><strong>Status:</strong></td>
<td style="padding:3px">{{test.Status}}</td>
</tr>
</span>
</table>
</div>
</ion-item>
</ion-list>
但是表格数据的颜色仍然没有改变。可能是什么问题呢?我是否错误地使用了 ng-if 和 ng-style ?谢谢!
更新 1:使用 @SSH 提供的见解,我使用以下代码更新了我的 Controller :
HTML:
<ion-list>
<ion-item ng-repeat="test in tests" class ="item-text-wrap" style="height:40%">
<a href="#/tab/test/test-detail/{{test.ID}}">
<div style="width:80%; float:left;">
<table>
<span ng-style="calculateStyle()">
<tr>
<td> <strong>Remark: </strong></td>
<td style="padding:3px">{{test.Remark}}</td>
</tr>
<tr>
<td><strong>Status:</strong></td>
<td style="padding:3px">{{test.Status}}</td>
</tr>
</span>
</table>
</div>
</ion-item>
</ion-list>
Controller :
$scope.calculateStyle = function() {
var style={}
console.log('test3: '+$scope.tests.Status);
console.log('test6: '+$scope.Status);
if ($scope.Status == 'Cleared') {
style.color='green';
console.log('Viola');
}
else{
console.log('GG');
}
return style;
}
})
但是 Controller 中返回的结果仍然为空/未定义。 test3 和 test6 返回“未定义”,而 If 语句返回“GG”。可能是什么问题呢?谢谢!
更新 2:使用 SSH 答案,我修改为以下内容:
HTML:
<span ng-style="calculateStyle(test)">
Controller :
$scope.calculateStyle = function(test) {
var style={}
if (test.Status == 'Cleared') style.color='green';
return style;
}
但是 Controller 上的测试变量仍然未定义。使用 $scope.test 也不起作用。可能是什么问题?
最佳答案
是的,你确实用错了它。您需要传递一个由样式名称和条件组成的对象:
<span ng-style="{color:(test.Status == 'Cleared')?'green'}">
或者更好地使用 Controller 中的函数来计算并返回样式对象,以保持模板干净:
<span ng-style="calculateStyle(test)">
然后在你的 Controller 定义中
$scope.calculateStyle = function(test) {
var style={}
if (test.Status == 'Cleared') style.color='green';
return style;
}
关于html - Angular Ng-If Ng-Style 不改变表格字体颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32495014/