'Separating ViewValue and ModelValue in Angular for a text input
I need to convert a custom element that takes account numbers as input like ABCD1234 and make it display as ****1234. While saving this value/submitting the form I want the value to go as ABCD1234 ie the true value. I have tried making use of $formatters but it seems to be changing the model value as well and saving the * in the value.
How do I separate the view value and model value so that the users see only last 4 digits but form saves true value entered.
The regex looks for all but last four digit and replaces with *
'use strict';
// @ngdoc directive
// @description
// directive for masking NPI(Non-public Information) inputs with asterisks.
angular.module('MyAPP').directive('npiMask', function() {
return {
require: 'ngModel',
link: function($scope, element, attrs, modelCtrl) {
modelCtrl.$formatters.push(function(inputValue) {
var transformedInput = inputValue.toString().replace(/.(?=.{4,}$)/g, '*');
if (transformedInput !== inputValue) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
<input-text
name="accountNum"
label="{{'LOAN_REPAY.ADD_LOAN.ACCOUNT_NUM_LABEL' | translate}}"
ng-model="vm.model.formData.loanDetails.accountNum"
is-required="true"
maxlength="35"
locked="vm.isSummaryView"
size="4"
ui-mask
npi-mask
>
Change view value without change model value
^ this did not work for me.
Solution 1:[1]
Ended up using this:
'use strict';
// @ngdoc directive
// @description
// directive for masking NPI(Non-public Information) inputs with asterisks.
angular.module('myApp').directive('npiMask', 'constants', function(constants) {
return {
require: 'ngModel',
link: function($scope, element, attrs, modelCtrl) {
var temp = '';
element.on('focusin', function() {
element[0].querySelector('#' + modelCtrl.$name).value = temp;
});
element.on('focusout', function() {
temp = modelCtrl.$modelValue;
var transformedInput = temp.toString().replace(constants.patterns.spacesInTheEnd, '*');
element[0].querySelector('#' + modelCtrl.$name).value = transformedInput;
});
}
};
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | feltspar |
