Santosh
Santosh

Reputation: 885

AngularJS - Using custom filter in ng-repeat for prefixing comma

Need to remove comma if value is empty works good if I have value present at start or middle; But same doesn't work in this scenario.

app.filter('isCSV', function() {
  return function(data) {
    return (data !== '') ? data + ', ' : '';
  };
});

Angularjs ng repeat for addressline - Plunker

Upvotes: 0

Views: 61

Answers (3)

Reddog
Reddog

Reputation: 15579

I would instead operate on arrays of properties and use a pair of filters, one to remove empty values, and one to join the array.

This way it's very explicit about what properties you are displaying.

<body ng-controller="MainCtrl">
  <ul>
    <li ng-repeat="item in details">
      {{ [ item.address0, item.address1, item.address2, item.address3] | removeEmpties | joinBy:', ' }}
    </li>
  </ul>
</body>

With the following filters:

app.filter('removeEmpties', function () {
    return function (input,delimiter) {
        return (input || []).filter(function (i) { return !!i; });
    };
});

app.filter('joinBy', function () {
    return function (input,delimiter) {
        return (input || []).join(delimiter || ',');
    };
});

Here's the updated Plunkr

Upvotes: 1

Icycool
Icycool

Reputation: 7179

I would prefer writing a function instead of adding a filter so many times.

$scope.mergeAddresses = function(item) {
  var address = item.address0;

  [1,2,3].forEach(function(i) {
    var add = item["address"+i];

    if (!add) return;

    address += (address ? ", " : "") + add;
  });

  if (address) address += ".";

  return address;
}

Plunker

Upvotes: 0

jitender
jitender

Reputation: 10429

Tricky but should work in your case Also no filter need

{{ item.address0 }} <span ng-if="item.address1">,
</span> {{ item.address1}}<span ng-if="item.address2">,</span>{{ 
item.address2}}
<span ng-if="item.address3">,</span>{{ item.address3}}

Here is working example

Upvotes: 0

Related Questions