AngularJS dynamically changes ngMask

I need to dynamically change the mask.

So I make this directive to handle:

link: function($scope, $element, $attrs, ngModel) {
    $scope.$watch($attrs.ngModel, function(value) {
        if (value.length > 4) {
            $element.attr('mask', '9999  9999');
        else {
            $element.attr('mask', '99999999');


The mask is applied, I check the DOM, but there is no effect.

What am I missing here?


source to share

3 answers

Can you do this logic in dom instead of link? Modifying attr probably won't do anything since it has already been parsed and it might not be looking at it.

ng-model="maskModel" mask="{{ maskModel.length > 4 ? '9999  9999' : '99999999' }}"




I know this is not what you are asking, but it might help others to come here. Defining an optional character is a good alternative. To do this, just add '?' after the character you want to be optional:


This is great for inputs like Brazilian phone numbers, which can be either 8 or 9 characters long.



Use attrs.$observe(..)

instead $scope.$watch (..)




All Articles