Skip to content

Commit

Permalink
Changing the way i deal with value, this approach makes this directiv…
Browse files Browse the repository at this point in the history
…e apply masks when it loads
  • Loading branch information
Wender Lima committed Jun 10, 2015
1 parent 30967a0 commit 2812802
Showing 1 changed file with 14 additions and 9 deletions.
23 changes: 14 additions & 9 deletions src/angular-simple-mask.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ angular.module('angularMask', [])
.directive('angularMask', function() {
return {
restrict : 'A',
link: function($scope, el, attrs) {
require: 'ngModel',
link: function($scope, el, attrs, model) {
var format = attrs.angularMask,
arrFormat = format.split('|');

Expand All @@ -13,8 +14,16 @@ angular.module('angularMask', [])
return a.length - b.length;
});
}
function mask(o) {
var value = o.value.replace(/\D/g,'');
model.$formatters.push(mask);
model.$parsers.push(function (value) {
model.$viewValue = mask(value);
var modelValue = parseInt(String(value).replace(/\D/g,''));
el.val(model.$viewValue);
return modelValue;
});

function mask(val) {
var value = String(val).replace(/\D/g,'');
if(arrFormat.length > 1){
for(var a in arrFormat){
if(value.replace(/\D/g,'').length <= arrFormat[a].replace(/\D/g,'').length){
Expand All @@ -37,12 +46,8 @@ angular.module('angularMask', [])
}
mI++;
}
o.value = newValue;
return newValue;
}
el.bind('keyup keydown', function(e) {
var keyList = [8,37,39,46];
if(keyList.indexOf(e.keyCode) == -1)mask(this);
});
}
};
});
});

0 comments on commit 2812802

Please sign in to comment.