Search code examples
angularjsmasking

Apply generic mask via filter?


I'm currently using ngMask to handle masking for user input. It works great, but, AFAIK, can only be used on input elements. I now need to mask this same data for display. For example, in a table, I would hope to display item.ssn = 123456789 as 123-45-6798.

What is the best way to do this? I understand I can make custom filters, but was wondering if there was a generic way to do this for all text. Like this if you could extend the ngMask functionality...

<td><span mask="999-99-9999">{{item.ssn}}</span></td>

or as a filter...

<td>{{item.ssn|filter:'999-99-9999'}}</td>

Solution

  • You need to implement a filter. You can rely on MaskService provided with ngMask:

    angular.module('myModule').filter('mask', ['MaskService', function(MaskService) {
      return function(text, mask) {
        var result, 
            maskService = MaskService.create(),
    
        if (!angular.isObject(mask)) {
          mask = { mask: mask }
        }
    
        maskService.generateRegex(mask).then(function() {
          result = maskService.getViewValue(text).withDivisors() 
        }
    
        return result;
      }
    }])
    

    Then:

    <td>{{item.ssn | mask:'999-99-9999'}}</td>