JSFiddle - React, Tailwind, and code Playground

by abuhamzah

HTML

<div ng-app="myApp">
    <h3>input type="text" does not add up</h3>
    A:<input type="text" ng-model="a1" numbers-only="numbers-only" maxlength="4"/>
    <br/>
    B:<input type="text" ng-model="b1" numbers-only="numbers-only" maxlength="4" />
    <br>
    C:<input type="text" ng-model="c1" numbers-only="numbers-only" maxlength="4"/>
    <br/>
    D:<input type="text" ng-model="d1" numbers-only="numbers-only" maxlength="4" />
    <br>
   Amount tendered (E): <input type="text" ng-model="e1" numbers-only="numbers-only"   />
    <hr/>
     <h3>{{ e1 - (a1+b1+c1+d1) | currency}} </h3>  
   
    <BR> 
       <h3>input type="number" directive does not work</h3>
    A:<input type="number" ng-model="aa1" numbers-only="numbers-only" maxlength="4"/>
    <br/>
    B:<input type="number" ng-model="bb1" numbers-only="numbers-only" maxlength="4" />
    <br>
    C:<input type="number" ng-model="cc1" numbers-only="numbers-only" maxlength="4"/>
    <br/>
    D:<input type="number" ng-model="dd1" numbers-only="numbers-only" maxlength="4" />
    <br>
   Amount tendered (E): <input type="number" ng-model="de1" numbers-only="numbers-only"   />
    <hr/>
     <h3>{{ ee1 - (aa1+bb1+cc1+dd1) | currency}} </h3>  
</div>

JavaScript

angular.module('myApp', []).directive('numbersOnly', function(){
   return {
     require: 'ngModel',
     link: function(scope, element, attrs, modelCtrl) {
       modelCtrl.$parsers.push(function (inputValue) {
           // this next if is necessary for when using ng-required on your input. 
           // In such cases, when a letter is typed first, this parser will be called
           // again, and the 2nd time, the value will be undefined
           if (inputValue === undefined) return '' 
           var transformedInput = inputValue.replace(/[^0-9+.]/g, ''); 
           if (transformedInput!==inputValue) {
              modelCtrl.$setViewValue(transformedInput);
              modelCtrl.$render();
           }         

           return transformedInput;         
       });
     }
   };
});