AngularJS基于键值对数组格式化数据

时间:2014-09-29 03:28:51

标签: javascript arrays angularjs

我有下面带Angular的HTML,它只是循环遍历每个结果并打印出来:

<tr ng-repeat="transaction in transactions | filter:search">
    <td>{{transaction.created}}</td>
    <td><a href="#/transactions/{{transaction.id}}">{{transaction.type}}</a></td>
    <td>{{transaction.amount}}</td>
</tr>

但是,type的数据库值是发送,接收,购买和销售。当它在视图中显示时,我希望它是您所期望的,动词(发送,接收,购买,销售)。

如何使用db值的键值对创建一个JavaScript数组来显示值,并显示该数组中与键匹配的值(在Angular中)?

1 个答案:

答案 0 :(得分:1)

假设您获得的types类似于:

  • 200 for sent
  • 150收到
  • 25 for buying
  • 354 for sold

您可以创建一个简单的过滤器,如下所示:

app.filter('typeToString', function(){
    var types = {'200':'sent', '150':'received', '25':'bought', '354':'sold'};
    return function(type){
         return types[type];
    };
})

并像这样使用它:

<tr ng-repeat="transaction in transactions | filter:search">
    <td>{{transaction.created}}</td>
    <td><a href="#/transactions/{{transaction.id}}">{{transaction.type|typeToString}}</a></td>
    <td>{{transaction.amount}}</td>
</tr>

Working Example

另一方面,如果您获得的types类似于:

  • 0表示已发送
  • 1 for received
  • 2 for buying
  • 3 for sold

然后你的过滤器可能是这样的:

app.filter('typeToString', function(){
    var types = ['sent', 'received', 'bought', 'sold'];
    return function(type){
         return types[type];            
    };
})

Working Example