Angularjs format input number when typing example

In this example i will show how to make format input number when typing in angularjs, we will use ng-changed event to do that. Of course you also use other way to do that.
Our goal:
Input : 100 => change to 100
Input : 1000 => change to 1,000
Input : 10000 => change to 10,000
Input : 100000 => change to 100,000
.....
And
Input : 100000.450 => change to 100,000.450

I hope that after got this example you can customize and make a common function related it.

Full code here



 <!DOCTYPE html>  
 <html xmlns="http://www.w3.org/1999/xhtml">  
 <head>  
   <title></title>  
   <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.2/angular.min.js"></script>  
   <script src="http://code.angularjs.org/1.2.16/angular.js"></script>  
   <script src="http://code.angularjs.org/1.2.16/angular-resource.js"></script>  
   <script>  
     myWebApp = angular.module('myWebApp', []);  
     myWebApp.controller("Controller01", function ($scope) {  
       $scope.ngchanged = function (val) {  
         var parts = val.toString().split(".");  
         parts[1] = parts[1] ? "." + parts[1] : ".";  
         if (val.indexOf(".") != -1)  
           $scope.iputval = numberWithCommas(parts[0]) + parts[1];  
         else  
           $scope.iputval = numberWithCommas(parts[0]);  
       };  
       function numberWithCommas(n) {  
         while (n.toString().indexOf(",") != -1)  
         {  
           n = n.replace(",", "");  
         }  
         return n.replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");  
       }  
     });  
   </script>  
 </head>  
 <body ng-app="myWebApp">  
   <div ng-controller="Controller01">  
     <p>Input number example: 100000 or 100000.450</p>  
     <input type="text" ng-model="iputval" ng-change="ngchanged(iputval)" />  
   </div>  
 </body>  
 </html>  

Demo at Plunker

Thanks for your time reading. Hope it helps!


No comments:

Post a Comment

Popular Posts