3

Say for example I have the following code (pseudo):

<div ng-repeat=range>{{ $index }}</div>

The result would be

1 2 3 4 5 6 ...

How could I go about changing the code above so that the indexes are printed

001 002 003 004 005 006? (so that the index is printed as 3 digits)

3
  • possible duplicate of How to output integers with leading zeros in JavaScript Commented Jun 2, 2013 at 9:43
  • @hexblot The possible duplicate you linked to itself seems itself to have been previously marked as a duplicate of another question... Commented Jun 2, 2013 at 10:22
  • 1
    @hexblot Creating an AngularJS filter was the big key to answering this question. I don't think this should be considered as a duplicate to the question linked. Commented Jun 2, 2013 at 16:12

1 Answer 1

2

You could do this pretty easily with a filter.

First, define it like so:

myModule.filter("tripleDigit", function() {
  return function(number) {
    if (number !== null && number !== undefined) {
      var str = "" + number;
      while (str.length < 3) str = "0" + str;
      return str;
    }
  };
});

Then you can pipe $index into it:

<div ng-repeat=range>{{ $index | tripleDigit }}</div>

Here's an example that defines a filter called pad that allows you to pass in how many digits to pad as an argument: http://jsfiddle.net/BinaryMuse/64ycY/

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

1 Comment

Nice answer. I was never too sure how to go about implementing filters and the fiddle example has also taught me just how. Thanks!

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.