Elaine Byene
Elaine Byene

Reputation: 4142

Angular 4 - Convert number to words

My output {{total.number}} is in number format which is 1. However, I want to convert that into one. I need it for 1-6 digits and the output be shown as one - six.

How do I got about it? I see only JS examples but not the Angular method.

I got this example: https://jsfiddle.net/lesson8/5tt7d3e6/ but I feel this is an overkill to achieve what I'm trying to do which is to convert the numbers 1 to 6 only.

Upvotes: 5

Views: 5409

Answers (2)

rtn
rtn

Reputation: 2034

Would use an object and access the desired value using bracket notation:

$scope.numbers = {
            0: 'zero',
            1: 'one',
            2: 'two',
            3: 'three',
            4: 'four',
            5: 'five',
            6: 'six'
        }

{{this.numbers[total.number]}}

You would be best to encapsulate the above logic into a pipe / filter

Upvotes: 2

Mihai Alexandru-Ionut
Mihai Alexandru-Ionut

Reputation: 48357

First of all, you need to define an array with your elements and bind input value to one variable, for instance, ng-model="number".

As time as you typed into the input the value of the number is modified(digest cicle does this) and that mean you can display your desired output by passing the number as index for your words array.

<div id="word">{{words[number]}}</div>

function MyCtrl($scope) {
  $scope.number=1;
  $scope.words= ['','One','Two','Three','Four','Five','Six'];
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
  <div ng-controller="MyCtrl">
    <input type="text" ng-model="number" />
<div id="word">{{words[number]}}</div>
  </div>
</div>

Upvotes: 2

Related Questions