0

My goal is to create an angular filter that could be placed on a textarea or input such that when a user types text that matches a predefined regular expression, the text would be identified and replaced with a masked form of that text.

Is this possible using a filter? Or should I be approaching it differently? I'd provide what I've started, but it's so far off that I'm not sure it would help at all. Even a solid starting point and confirmation that I'm approaching this correctly (or not), would be helpful.

br.julien
  • 3,420
  • 2
  • 23
  • 44
Josh
  • 1,876
  • 3
  • 21
  • 35
  • Add some codes, what have you tried right now? – lin Apr 23 '17 at 00:04
  • nothing wrong with writing it as a filter. Can use that filter inside a directive to update ngModel if needed by using `$filter` service. So it will be versatile regardless of how you finally implement it. Or write it in a service. Whatever you do it will be easy to move around if needed – charlietfl Apr 23 '17 at 00:16

1 Answers1

0

It looks like a directive is the easiest way to do this because filters can't be included on ng-model bindings.

Based on that, and heavy help (this could probably be marked as a duplicate question) from the 2nd answer on this page, I got it working the way I wanted.

angular.module("app").directive('customValidation', function () {
        return {
            require: 'ngModel',
            link: function (scope, element, attrs, modelCtrl: ng.INgModelController) {

                modelCtrl.$parsers.push(function (inputValue) {

                    var transformedInput = inputValue.replace(/microsoft/i, "W3Schools");


                    if (transformedInput != inputValue) {
                        modelCtrl.$setViewValue(transformedInput);
                        modelCtrl.$render();
                    }

                    return transformedInput;
                });
            }
        };
    });

<textarea ng-model="vm.text" ng-trim="false" custom-validation></textarea>
Community
  • 1
  • 1
Josh
  • 1,876
  • 3
  • 21
  • 35