javascript - AngularJS dynamically change ngMask - Stack Overflow

I need to dynamically change a mask. So I'm making this directive to handle it:link: function($sco

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 (..).

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745434310a4627538.html

相关推荐

  • javascript - AngularJS dynamically change ngMask - Stack Overflow

    I need to dynamically change a mask. So I'm making this directive to handle it:link: function($sco

    10小时前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信