简体   繁体   中英

AngularJS dynamically change ngMask

I need to dynamically change a mask.

So I'm making this directive to handle it:

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 being applied, I'm checking the DOM, but there's no effect whatsoever.

What I am missing here?

Can you do that logic in the dom instead of the link? Modyfing the attr probably won't do anything as it's already been parsed and it might not be watching it.

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

I know this isn't what you are asking but it may help others coming here. A good alternative is to define an optional character. To do that just add an '?' after the character you want to be optional:

mask="9?9999-9999"

This is great for inputs like Brazilian phone numbers, which can have both 8 or 9 characters.

使用attrs.$observe(..)而不是$scope.$watch (..)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM