Question

Is it possible to create a mask in angularJS that looks like this

02years 07months.

And when the user clicks on the text box it should change to the following text

0207

Thanks a ton!

Was it helpful?

Solution

You can use a directive to bind to focus and blur events. http://plnkr.co/sFyfYstSlQpZtLUGbmwh

<input type="text" year-month data="foo.bar"></input>  

app.directive('yearMonth', function() {
    return {
        restrict: 'A',
        scope: {
          data: '='
        },
        link: function(scope, element, attr) {
          var re = /(\d{2})(\d{1,2})()/;

          function addMask(text) {
            return text.replace(re, "$1years$2months");
          }

          function removeMask(text) {
            return text.replace(re, "$1$2");
          }

          element.val(addMask(scope.data));

          element.bind('blur', function () {
            scope.$apply(function() {
              var text = element.val();

              scope.data = text;
              element.val(addMask(text));
            });
          });

          element.bind('focus', function () {
            scope.$apply(function() {
              element.val(removeMask(scope.data));
            });
          });
        }
    };
});

But, be sure to read this question: How to do two-way filtering in angular.js? There is likely a preferable solution that users the parsers and formatters of ngModelController.

OTHER TIPS

Yep, look into the ui-mask directive.

http://angular-ui.github.io/ui-utils/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top