0

So i have an ng-repeat which is conditioned by an ng-if.

That's the div

<div class="fav-prod-customised>
    <p ng-repeat="ingredient in product.options"
         ng-if="ingredient.default_quantity == 0 && 
         ingredient.entry.quantity > 0">
                              {[{ingredient.entry.full_name}]}
         <span ng-if="!$last">,</span>
    </p> . 
</div>`

After every ingredient i want a comma, until the last ingredient where i don't want a comma. '$last' property is not working because the last displayed item is not the last item from the array.

How can i solve that?

Vikas Gupta
  • 1,183
  • 1
  • 10
  • 25
hyena
  • 75
  • 3
  • 11

2 Answers2

1

Replace ng-if in ng-repeat with Custom Filter:

Create a custom filter:

app.filter("myFilter", function() {
  return function (list) {
    return list.filter(function(item) {
       return item.default_quantity == 0 && 
              item.entry.quantity > 0;
    });
  };
})

Use that filter instead of using the ng-if directive:

   <p ng-repeat="ingredient in product.options | myFilter">
      {{ingredient.entry.full_name}} {{$last}}
         <span ng-hide="$last">,</span>
   </p> .

This technique is more efficient because it avoids adding watchers and child scopes for each ng-if. Also $last and the other special properties of the ng-repeat directive will work as expected.

The DEMO

angular.module("app",[])
.filter("myFilter", function() {
  return function (list) {
    return list.filter(function(item) {
       return item.default_quantity == 0 && 
              item.entry.quantity > 0;
    });
  };
})

.controller("ctrl", function($scope) {
  var vm=$scope;
  vm.product = { options: [
    { default_quantity: 0,
      entry: { quantity: 4, full_name: "fullname0"}
    },
    { default_quantity: 0,
      entry: { quantity: 4, full_name: "fullname1"}
    },
    { default_quantity: 1,
      entry: { quantity: 4, full_name: "fullname2"}
    },
    ]
  };
})
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app" ng-controller="ctrl">
    GOOD
    <p ng-repeat="ingredient in product.options | myFilter">
      {{ingredient.entry.full_name}} {{$last}}
         <span ng-hide="$last">,</span>
    </p> .
    <hr>BAD
    <p ng-repeat="ingredient in product.options"
         ng-if="ingredient.default_quantity == 0 && 
         ingredient.entry.quantity > 0">
      {{ingredient.entry.full_name}} {{$last}}
         <span ng-hide="$last">,</span>
    </p> .
  </body>
Community
  • 1
  • 1
georgeawg
  • 48,608
  • 13
  • 72
  • 95
0

Use a ternary, {{$last ? '' : ', '}}:

<div class="fav-prod-customised">
    <p ng-repeat="ingredient in product.options" 
       ng-if="ingredient.default_quantity == 0 && ingredient.entry.quantity > 0">
        {[{ingredient.entry.full_name}]}
        {{$last ? '' : '<span>, </span>'}}
    </p> 
</div>
Stuart
  • 6,630
  • 2
  • 24
  • 40