AngularJS逗号分隔为JSON格式

时间:2014-12-19 06:21:47

标签: json angularjs angularjs-ng-repeat

我在使用ng-repeatng-if分隔逗号时遇到问题。

我想以逗号分隔结果,但最后一项也包括comma

我的期望是:AAA, CCC, EEE

但输出结果如下:AAA, CCC, EEE,

ng-repeat块如下:

<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>

此处,policiesInfo与查找表连接,JSON格式的输出为:

对于每个ProviderId,它将包含6个查找记录:

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 }
]

此处$last被视为PolicyId : 6$index被视为PolicyId : 1

2 个答案:

答案 0 :(得分:4)

你的实际$ last(FFF)没有呈现,因为它有HasChecked: false,所以你看到的最后一个逗号","是为EEE呈现的那个。

要实现您的目标,您需要首先过滤 out HasChecked: false,以便$ last适用于已过滤的数组:

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

plunker

答案 1 :(得分:1)

我通过添加一个过滤器来实现结果:

<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;
};