2

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?

1 Answer 1

8

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().

Sign up to request clarification or add additional context in comments.

2 Comments

delete the first input and there's a floating coma at the begining
@gyc - Yes, I realized this right after I posted it. I've updated the code, and the link to a new fiddle.

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.