0

I have data like this:

var user = {
  name: 'John Doe',
  property: 'value',
  ranks: [
    {name: 'One', property: 'value'},
    {name: 'Two', property: 'value'}
  ]
}

I want to output somewhere in the page all user's rank names divided by commas, like this:

<td>John Doe</td>
<td>One, Two</td>

How to do this?

Pure javascript isn't working:

<td>{{user.name}}</td>
<td>{{user.ranks.map(function(r) { return r.name }).join(', ')}}</td>

I think here should be an Angular filter or something, but can't find anything.

2
  • Are there multiple users, or just one user? Commented Jul 25, 2014 at 8:43
  • Sure there will be multiple users, but I want to do this with each user separately. Commented Jul 25, 2014 at 13:47

2 Answers 2

3

You can't write JS like that in your templates. The angular way would be to use a filter:

app.filter("usersFilter" , function () {
        return function(user) {
           return user.ranks.map(function(r) { return r.name }).join(', ');
        }
}

and in your HTML:

<td>{{ user | usersFilter}}</td>
Sign up to request clarification or add additional context in comments.

Comments

1

Finally I did it so:

  1. Wrote distinct map and join filters with parameters:

    app.filter("map", function() {
      return function(collection, attribute) {
        return collection.map(function(object) {
          var attr = object[attribute];
          return (typeof attr === "function") ? attr() : attr;
        });
      }
    });
    
    app.filter("join", function() {
      return function(collection, separator) {
        return collection.join(separator);
      }
    });
    
  2. And then in template

    <td>{{user.ranks | map:'name' | join:', ' }}</td>
    

And now it works in a way I wanted.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.