【问题标题】:Angular Ng-If Ng-Style not changing the table font colourAngular Ng-If Ng-Style 不改变表格字体颜色
【发布时间】:2015-12-06 08:02:59
【问题描述】:

我有以下代码,它是一个离子列表,用于填充检索到的数据。我试图根据状态响应将其颜色编码为不同的颜色。

<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 提供的见解,我使用以下代码更新了我的控制器:

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>

控制器:

 $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;
  }
})

但是控制器中返回的结果仍然是空的/未定义的。 test3 和 test6 返回我“未定义”,而 If 语句返回我“GG”。可能是什么问题呢?谢谢!

更新 2:使用 SSH 答案,我修改为以下内容:

HTML:

<span ng-style="calculateStyle(test)">

控制器:

$scope.calculateStyle = function(test) {
    var style={}
    if (test.Status == 'Cleared') style.color='green';
    return style;
}

但控制器上的测试变量仍未定义。使用 $scope.test 也不起作用。可能是什么问题?

【问题讨论】:

  • test.Status 不需要大括号吗?
  • @JoeLloyd 是的,我愿意,即填充从控制器检索到的数据。
  • 不允许在&lt;tr&gt; 周围添加&lt;span&gt; 元素。为什么不使用 css 类?
  • @JoeLloyd 已更改但仍无法正常工作,但感谢您的提醒!
  • @MikeVranckx 让我尝试使用 css 类,谢谢您的反馈!

标签: html css angularjs ionic


【解决方案1】:

是的,你确实用错了。您需要传递一个由样式名称和条件组成的对象:

<span ng-style="{color:(test.Status == 'Cleared')?'green'}">

或者更好地使用控制器中的函数来计算并返回样式对象,以保持模板干净:

<span ng-style="calculateStyle(test)">

然后在你的控制器定义中

$scope.calculateStyle = function(test) {
    var style={}
    if (test.Status == 'Cleared') style.color='green';
    return style;
}

【讨论】:

  • 嗨,我如何使用函数返回样式对象?使用$范围?如果你有空,你能解释一下吗?谢谢!
  • 再次嗨,它不适用于您给伙伴的第一个解决方案。谢谢!
  • 从控制器的函数中,$scope.test.Status 返回空值。
  • 我的错——我没有注意到你的重复声明......现在将更改代码
  • 是的,我马上更新了——你需要通过测试作为参数
猜你喜欢
  • 2017-08-05
  • 1970-01-01
  • 2016-11-15
  • 1970-01-01
  • 2014-08-15
  • 2012-05-31
  • 1970-01-01
  • 2016-12-24
  • 2020-09-09
相关资源
最近更新 更多