Search code examples
angularjsangular-filters

4 digit number formatting in Angularjs


There is this requirement for my application where-in the user types a value in the text box field and parallely shown in a box below. BUT the problem is I want to have format something like this 1234-1234-1234 (including the dashes). Can that be possible. I've tried using the angular filters but seems to be not working.


Solution

  • Assuming you are using Angular 1.X, I would suggest you to create a directive for this which will give a better control on the element.

    Try below

    var app = angular.module('TestApp', []);
    
    app.directive('inputFormat', function() {
      return {
        restrict: 'AE',
        replace: true,
        template: '<input type="text" ng-model="inputVal" placeholder="Enter a number" />',
        link: function(scope, elem, attrs) {
          elem.bind('keyup', function() {
            var inputElm = elem.val().split("-").join(""); // remove hyphens
            if (inputElm.length > 0) {
              inputElm = inputElm.match(new RegExp('.{1,4}', 'g')).join("-");
            }
            elem.val(inputElm);
          });
        }
      };
    });
    
    app.controller('MyCtrl', function($scope) {
      $scope.search = function(element) {
        console.log(element);
        alert("keypressed. Value so far is: " + element.val());
      };
    });
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="TestApp">
      <div ng-controller="MyCtrl">
        <input-format/>
      </div>
    </div>

    Here is the http://jsfiddle.net/anandgh/6unogzyh/

    Hope this helps