使用格式化程序更改viewvalue时保持modelvalue

时间:2017-06-01 00:55:20

标签: javascript angularjs angular angular-ngmodel

我有一个文本框,并希望在输入时将用户输入显示为*,并将输入保存为正常示例。 123456789 -> ***_***_***

给定一个像这样的输入字段:

<input class="form-control" type="text"  name="secretNumber" 
ng-model="vm.report.fields.secretNumber" hr-secret-number/>

给出这样的指令:

module app.directives {
    'use strict';

    class SecretNumber implements ng.IDirective {
        require = 'ngModel';
        restrict = 'A';

        formatSsn = (secret: string): string  => {
            return secret.replace(/[0-9]/g, '*');
        };

        link = ($scope, $element, $attrs, $ngModel: ng.INgModelController) => {
            var onModelChanged = () => {
                $ngModel.$setViewValue(this.formatSsn($ngModel.$modelValue));
                $ngModel.$render();
                console.log($ngModel);
            };

            $ngModel.$viewChangeListeners.push(onModelChanged);

            $ngModel.$formatters.push((value) => {
                return this.formatSsn($ngModel.$modelValue);
            });

            if (!$attrs['hrAllowRegex'] || !$attrs['maxlength'] || !$attrs['ngMinlength']) {
                $attrs.$set('hr-allow-regex', '[0-9]');
                $attrs.$set('maxlength', 14);
                $attrs.$set('ngMinlength', 14);
            }
        };


        static factory():ng.IDirectiveFactory {
            var directiveFactory:ng.IDirectiveFactory = () => new SecretNumber();

            return directiveFactory;
        };
    }

    angular.module('app').directive('hrSecretNumber', SecretNumber.factory());
}

如何在修改viewvalue时保留modelvalue,所以在文本框中它会显示****,而我可以在数据库中保存为1234例如。

console.log的结果如下所示

NgModelController {$viewValue: "****", $modelValue: "****", $$rawModelValue: "****", $validators: Object, $asyncValidators: Object…}

而不是

NgModelController {$viewValue: "****", $modelValue: "1234", $$rawModelValue: "1234", $validators: Object, $asyncValidators: Object…}

0 个答案:

没有答案