Search code examples
javascriptangularjsangularjs-filter

Create an AngularJS filter to remove regular expression matches and replace with masked text in textarea


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.


Solution

  • 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>