2

I have an issue with the comma separated with ng-repeat and ng-if.

I want to make the result as comma separated, but the last item is also include the comma.

My Expectation is : AAA, CCC, EEE

But the output is coming as : AAA, CCC, EEE,

The ng-repeat block is as below:

<div ng-repeat="provider in providersInfo">
    <span ng-repeat="policy in policiesInfo | filter:{ProviderId : provider.ProviderId }:true">
        <span ng-if="policy.HasChecked">{{ policy.PolicyName }}{{$last ? '' : ', '}}</span>
    </span>

    <!-- or -->

    <span ng-repeat="policy in policiesInfo | filter:{ProviderId : provider.ProviderId }:true">
        <span ng-if="policy.HasChecked">{{$index == 0 ? '' : ', '}}{{ policy.PolicyName }}</span>
    </span>
</div>

Here, policiesInfo is join with lookup table, the output of JSON format is:

For each ProviderId it will contain 6 lookup records:

policiesInfo = [ 
    {PolicyId : 1, PolicyName: 'AAA', ProviderId: 25, HasChecked: true },
    {PolicyId : 2, PolicyName: 'BBB', ProviderId: 25, HasChecked: false },
    {PolicyId : 3, PolicyName: 'CCC', ProviderId: 25, HasChecked: true },
    {PolicyId : 4, PolicyName: 'DDD', ProviderId: 25, HasChecked: false },
    {PolicyId : 5, PolicyName: 'EEE', ProviderId: 25, HasChecked: true },
    {PolicyId : 6, PolicyName: 'FFF', ProviderId: 25, HasChecked: false }
]

Here $last is consider as PolicyId : 6 and $index is consider as PolicyId : 1

2 Answers 2

4

Your actual $last (FFF) is not rendered because it has HasChecked: false, so the last comma "," you're seeing is the one rendered for EEE.

To achieve what you want you'd need to filter out the HasChecked: false first, so that $last would apply to the filtered array:

<span ng-repeat="policy in policiesInfo | filter: {HasChecked: true, ProviderId: provider.ProviderId}">
   {{policy.PolicyName}}<span ng-if="!$last">,</span>
</span>

plunker

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

2 Comments

I solved the issue by adding 1 more filter, but your answer helped me too think about the filter by HasChecked
Your suggestion <span ng-repeat="policy in policiesInfo | filter: {HasChecked: true, ProviderId: provider.ProviderId}"> is working.
1

I achieved the result by adding one more filter:

<span ng-repeat="policy in policiesInfo | filter:{ProviderId : provider.ProviderId }:true | filter: checkedPolicies">
    <span>{{ insurancepolicy.PolicyTypeName }}{{$last ? '' : ', '}}</span>
</span>

$scope.checkedPolicies = function(policyItem) {
    return policyItem.HasChecked;
};

1 Comment

I forgot about your other filter - added it to the answer

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.