1

I have a array of objects with property 'name'.

<script>
function FriendsCtrl($scope) {
$scope.friends = [{
    email: ['abc', 'def'],
    name: "i'm noob"
}, {
    email: ['ghi', 'jkl'],
     name: "me 2"
},
{
    email: ['ghi', 'jkl'],
     name: "and me!"
}];
}
</script>

I want to list as string all names inside a div, separated with ',' I managed to do it this way, using underscore:

<span ng-repeat="email in friends">{{email.name}}{{$last ? '' : ', '}}</span>

Rez:

i'm noob, me 2, and me!

How to solve this problem using angular way?

Thanks!

Fiddle: http://jsfiddle.net/UJEnt/

Waiom
  • 35
  • 6

2 Answers2

1

in order to create this CSV like behavior, you can use a custom filter (documentation)

http://jsfiddle.net/c8DKB/3/

csv filter

myApp.filter('csv', function() {
    return function(values, property_name) {
        var result = '';
        for (var i = 0; i < values.length; i++) {
            var value = values[i];
            if (property_name) {
                value = value[property_name];
            }
            result += value;
            if (i + 1 != values.length) {
                result += ',';
            }
        }
        return result;
    };
});

usage

friends is the data source and name is the property

<div>{{friends | csv:'name'}}</div>

you can also use it without specifying property name (if you are dealing with a string array)

<div>{{another_string_array | csv}}</div>

result

http://jsfiddle.net/c8DKB/3/

Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129
1

JS:

angular.module('foo').filter('concat', function(input, field) {
    var result = [];

    for (var i = 0, ii = input.length; i < ii; ++i) {
        result.push(input[i][field]);
    }

    return result.join(', ');
});

HTML:

<span>{{ friends | concat:'name' }}</span>
Miraage
  • 3,334
  • 3
  • 26
  • 43