最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - AngularJS dynamically change ngMask - Stack Overflow

programmeradmin2浏览0评论

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?

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?

Share Improve this question edited May 5, 2015 at 13:14 cнŝdk 32.2k7 gold badges60 silver badges80 bronze badges asked May 5, 2015 at 12:51 Matheus LimaMatheus Lima 2,1433 gold badges33 silver badges49 bronze badges 2
  • some solution? I have the same problem. – Alberto Rojas Commented Apr 24, 2017 at 23:53
  • Hey, @Matheus Lima. Up to this moment, I've found a solution that actually works for your case, as it works for me. It seems you need to build a directive that changes the dynamic value on Angular, through data-binding, while using the $scope.$watch method. I can post an example as an answer – nath_in_code Commented Apr 26, 2017 at 20:55
Add a ment  | 

3 Answers 3

Reset to default 3

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 ing 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.

Use attrs.$observe(..) instead of $scope.$watch (..).

发布评论

评论列表(0)

  1. 暂无评论