0

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.

3
  • You can use input mask plugin for easily do that Commented Feb 27, 2018 at 6:02
  • Which version of angular is this? also show the code that you tried so far? Commented Feb 27, 2018 at 6:31
  • Where is your attempt what already you have tried?? Commented Feb 27, 2018 at 6:35

1 Answer 1

2

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

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

1 Comment

Thank you very much sir. The code is working so perfectly.

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.