lukaZawi lukaZawi - 4 months ago 5
AngularJS Question

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>

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?


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:


See this fork of your fiddle.

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