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?

+3


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' }}"

      

+2


source


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:

mask="9?9999-9999"



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

+2


source


Use attrs.$observe(..)

instead $scope.$watch (..)

.

0


source







All Articles