Is it possible to encrypt only the $modelValue
of a ngModel
using any algorithm, while keeping the view value in plain text?
I attempted to create a custom directive to achieve this:
angular.module('utilityModule').directive('encrypt', function() {
var aesUtil = new AesUtil(128, 10);
return {
restrict: 'A',
require: 'ngModel',
replace: false,
compile: function(tElem, tAttrs) {
var modelName = tAttrs['ngModel'];
var pattern = tAttrs['ngPattern']; // to check if there is ngPattern directive used.
return {
pre: function(scope, element, attrs, fn) {
// to avoid encrypting on every key press.
fn.$options = {
updateOn: 'blur'
};
fn.$parsers.push(function(value) {
//encrypt
console.log('parser invoked');
return value ? aesUtil.encrypt(modelName, modelName, modelName, value) : value;
});
fn.$formatters.push(function(value) {
//decrypt
console.log('formatter invoked');
return value ? aesUtil.decrypt(modelName, modelName, modelName, value) : value;
});
fn.$validators.pattern = function(){
// trying to overrule ngPattern directive. DOESN'T HELP!!
return true;
};
// Just for playing around
fn.$validators.amyValid = function(modelValue, viewValue) {
console.log('Custom validator invoked. modelValue=' + modelValue + ' and viewValue=' + viewValue);
return true;
};
},
post: function(scope, element, attrs, fn) {}
};
}
};
});
The custom directive works well, except when the ngPattern directive is used alongside ngModel. For instance:
<div class="table-responsive" ng-form="testForm">
<input name="test" type="text" ng-model="test" encrypt ng-pattern="/^[0-9]+$/"/>
<br>
{{test}}
</div>
What I'm looking for:
The ngPattern
directive should validate using the $viewValue
rather than the $modelValue
.
Is there a way to override the 'patternDirective' directive in the core angular.js
file?
Any other suggestions would also be appreciated...
UPDATE 1
I've noticed that not only ngPattern
, but also other validations like maxLength, minLength, max, min should be applied to the view value only.
UPDATE 2
My debugger indicates that the value passed to the patternDirective validator is the encrypted one. Please refer to the screenshot attached.https://i.sstatic.net/9E2px.png
UPDATE 3
Updating to angularjs 1.4.5 resolved the issue. It seems that in version 1.3.x, validation is done on the model value rather than the view value.