0

I am trying to print comma seperated values with successive loops but getting double comma.

Update:

Suppose i have data like this in my array:

 var carModel = [model:"1",model:"2"]; 
var carNames = [Name:"Abc",Name:"Xyz"]; 
var Price = 1000; 

Expected output:

  1 as Car1,2 as Car2,Abc as Name1,Xyz as Name2,1000 as price

Code:

 <div ng-repeat="data in carModel">
     {{data.model}}
     <div>as</div>
     Car{{ $index + 1 }} 
     <span ng-if="!$last">,</span>
 </div>

<div ng-repeat="data in carNames">
     {{data.Name}}
     <div>as</div>
     Car{{ $index + 1 }} 
     <span ng-if="!$last">,</span>
 </div>

 <span ng-if="carModel.length > 0 || carNames.length > 0" > , </span>
 <div>
  {{ Price }}
  <div>as</div> price
</div>

Now this gives me below output which contains double comma:

1 as Car1,2 as Car2,Abc as Name1,,Xyz as Name2,1000 as price
1
  • @ryanyuyu Stated in the top:1 as Car1, Commented Sep 21, 2016 at 15:17

2 Answers 2

4
<div ng-repeat="data in cars">
     {{data.model}}
     <div>as</div>
     Car{{ $index + 1 }} 
     <span ng-if="!$last">,</span>
 </div>

$last can be used to know if the current element is the last of your collection.

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

2 Comments

Ok this worked correctly but i am getting problem when i have 2 successive loops.See my updated question
Guess you have to work a little bit on your logic here to find the suitable conditions.
2

Other possible non-Angular solutions:

  • If this is merely a long string, and you're not doing anything else with the car data, just assemble the string in javascript with String.join().
  • Employ a css-based solution. For example, using the :last-of-type pseudo selector. For example:

    <div ng-repeat="data in cars" class="car">{{data.model}}
                               <div>as</div>
                               Car{{ $index + 1 }}
    </div>
    

    Css:

    .car::after {
      content: ',';
    }
    .car:last-of-type::after {
      content: '';
    }
    

    Demo on plunker

1 Comment

Thank you so much for the solution and this worked but only problem is that this car:last-of-type::after property is not working with span tag.only working with div

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.