0

I'm trying to use Input Mask jQuery plugin as a directive but getting the following error in Chrome's console errors.

TypeError: Cannot read property 'length' of undefined

My code

JS

var app = angular.module('app', ['ngResource']);

app.directive('inputMask', function(){
    return {
        restrict: 'A',
        link: function(scope, element){
             element.mask();
        }
    }
})

HTML

<input type="text" class="form-control input-mask" data-input-mask data-mask="{mask: 00/00/0000}" placeholder="eg: 23/05/2014">

http://plnkr.co/edit/Kp3SYS0cbIfVm1gTwtE0?p=preview

Please help me fix this.

Body
  • 3,608
  • 8
  • 42
  • 50

1 Answers1

1

The length error is because the element.mask() method need an attribute with the mask string you want to use. (in this case '00/00/0000'). So you have to change some things, first your directive:

var app = angular.module('app', ['ngResource']);

app.directive('inputMask', function(){
    return {
        restrict: 'A',
        scope: {
          inputMask: '='
        },
        link: function(scope, element){
          element.mask(scope.inputMask.mask);
        }
    }
})

And then in the html so you can set the mask in the element.

<input type="text" class="form-control" data-input-mask="{mask: '00/00/0000'}" placeholder="eg: 23/05/2014">

Here is a Plunker working:

http://plnkr.co/edit/BbJtsF9mWx4n29CfZajF?p=preview

Facundo Pedrazzini
  • 1,486
  • 14
  • 22
  • This so cool and thanks. I think whenever the plugin require something from a data-attribute, I need to handle in this way. Thank you very much for the answer and simple explanation. Love you... – Body May 26 '15 at 20:06