有条件地应用ng-repeat过滤器

时间:2013-06-20 05:38:24

标签: angularjs filter angularjs-ng-repeat

我有一个包含数字和值的文本混合的对象。我想将numbers过滤器应用于对象的值,当它是一个数字时(显然)。但是当它不是一个数字时,我会好起来只是吐出字符串。按原样,将| number应用于值会格式化数字,但将字符串值保留为空(毕竟,它们不是数字)。

我猜它必须是一个自定义过滤器(我还需要制作)。有没有办法在执行ng-repeat

时仅在HTML中执行此操作
<table>
      <tr ng-repeat="(metric, metricData) in data">
        <td>{{metric}}</td>
        <td>{{metricData | number}}</td>
      </tr>
</table>

$scope.data = { name:"this is the name", 
                score:48
                outcome:"as expected",
                attendance:820,
                total:212.34
              };

3 个答案:

答案 0 :(得分:18)

以下是使用ng-if(v1.1.5)从@callmekatootie获得的答案的备用版本:

<table>
    <tr ng-repeat="(metric, metricData) in data">
        <td>{{metric}}</td>
        <td ng-if="isNumber(metricData)">{{metricData | number}}</td>
        <td ng-if="!isNumber(metricData)">{{metricData}}</td>
    </tr>
</table>

这样做的好处是只对数字元素运行过滤器。在这种情况下,这可能没什么好处,但在其他更复杂的过滤器情况下可能会有用。要回答关于内置angular.isNumber的其他问题,@ callmekatootie会在范围函数isNumber中使用它,它只是在视图中使用内置函数的包装器。

Here is a fiddle

答案 1 :(得分:3)

您可以这样尝试 - 在您的控制器中,您可以使用一个功能来识别提供的值是字符串还是数字:

$scope.isNumber = function (value) {
    return angular.isNumber(value);
};

接下来,在您的视图中,您可以拥有以下内容:

<table>
    <tr ng-repeat="(metric, metricData) in data">
        <td>{{metric}}</td>
        <td ng-show="isNumber(metricData)">{{metricData | number}}</td>
        <td ng-hide="isNumber(metricData)">{{metricData}}</td>
    </tr>
</table>

因此,当metricData是一个数字时,它会被过滤,当它是一个字符串时,它会按原样输出。

答案 2 :(得分:3)

我知道这是旧的,但我认为最好的解决方案是将逻辑移到过滤器上。

app.filter("metricDataFilter", function($filter) {
    return function(value) {
      if(angular.isNumber(value)) {
          return $filter("number", value);  
      }

      return value;
    }  
}

这样HTML更简洁,而角度不需要重绘dom元素

<table>
    <tr ng-repeat="(metric, metricData) in data">
        <td>{{metric}}</td>
        <td>{{metricData | metricDataFilter}}</td>
    </tr>
</table>
相关问题