简体   繁体   中英

AngularJS formatting data based on array of key-value pairs

I have the HTML with Angular below, that simply loops through each result and prints it:

<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>

However, the database values of type are send, receive, buy, and sell. When it's displayed in the view, I want it to be as you could expect, a verb (sent, received, bought, sold).

How can I create a JavaScript array with key-value pairs of db value to display value, and display the value from that array where it matches the key (in Angular)?

Assuming that the types that you are getting are something like:

  • 200 for sent
  • 150 for received
  • 25 for bought
  • 354 for sold

You could just create a simple filter, like this:

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

And use it like this:

<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

On the other hand, if the types that you are getting are something like:

  • 0 for sent
  • 1 for received
  • 2 for bought
  • 3 for sold

Then your filter could be like this:

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

Working Example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM