Łukasz
Łukasz

Reputation: 2171

How to display variables values in a row with comma separator in angularjs

I have four variables and I want to display their values in a row with comma separator. I have something like this:

{{first}}<span ng-show="first != '' && (second != '' || third != '' || forth != '')">, </span>
{{second}}<span ng-show="second != '' && (third != '' || forth != '')">, </span>
{{third}}<span ng-show="third!= '' && forth != ''">, </span>
{{forth}}

It works (see jsfiddle) but looks awful. Do you have any idea how to achieve this (without adding next variable) in more smart, elegance or useful way?

Upvotes: 2

Views: 108

Answers (1)

Seth Flowers
Seth Flowers

Reputation: 9190

Look at the array.join function. You can add a function to your scope to do the join, and filter out empty values. For instance:

$scope.joined = function() {
  return [$scope.first, $scope.second, $scope.third, $scope.forth]
    .filter(function(i) { return i; })
    .join(', ');
};

Then in your markup:

{{joined()}}

See this fork of your fiddle.

See the MDN docs for Array.prototype.join() and Array.prototype.filter().

Upvotes: 8

Related Questions