Masking in AngularJS

若如初见. 提交于 2019-12-13 05:08:50

问题


Is it possible to create a mask in angularJS that looks like this

02years 07months.

And when the user clicks on the text box it should change to the following text

0207

Thanks a ton!


回答1:


You can use a directive to bind to focus and blur events. http://plnkr.co/sFyfYstSlQpZtLUGbmwh

<input type="text" year-month data="foo.bar"></input>  

app.directive('yearMonth', function() {
    return {
        restrict: 'A',
        scope: {
          data: '='
        },
        link: function(scope, element, attr) {
          var re = /(\d{2})(\d{1,2})()/;

          function addMask(text) {
            return text.replace(re, "$1years$2months");
          }

          function removeMask(text) {
            return text.replace(re, "$1$2");
          }

          element.val(addMask(scope.data));

          element.bind('blur', function () {
            scope.$apply(function() {
              var text = element.val();

              scope.data = text;
              element.val(addMask(text));
            });
          });

          element.bind('focus', function () {
            scope.$apply(function() {
              element.val(removeMask(scope.data));
            });
          });
        }
    };
});

But, be sure to read this question: How to do two-way filtering in angular.js? There is likely a preferable solution that users the parsers and formatters of ngModelController.




回答2:


Yep, look into the ui-mask directive.

http://angular-ui.github.io/ui-utils/



来源:https://stackoverflow.com/questions/22581945/masking-in-angularjs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!