使用:angularjs 1.4。
我需要编写一条指令,为ngModel和ngBind隐藏敏感数据(用星号'*'替换中间部分),但我还需要保留原始的,未屏蔽的数据,以便将其发送回后端服务器。
格式化部分不是问题,但我不知道如何保留原始数据。
我已经考虑过返回具有模糊和原始值的对象,但是由于涉及到ngBind,所以我不能依靠ngModelController来设置格式化程序和解析器。
这里是我到目前为止的代码:
app.factory('obfuscator', function() {
return {
obfuscate: obfuscate
};
function obfuscate(value) {
// assume undef, empty, etc have all been taken care of
let len = value.length;
let chunk = Math.floor(len / 3);
let masked = len - (chunk * 2);
return {
obfuscated: value.substr(0, chunk) + "*".repeat(masked) + value.substr(len - chunk, chunk),
original: value
};
}
}).directive('sensitive', ['obfuscator', function(obfuscator) {
return {
restrict: 'A',
priority: 1,
scope: {
model: '=ngModel'
},
link: function(scope, element, attrs, controller) {
scope.$watch('model', function() {
if (angular.isUndefined(scope.model)) return;
let val = obfuscator.obfuscate(scope.model);
scope.model = val.obfuscated;
});
attrs.$observe('ngBind', function() {
let val = obfuscator.obfuscate(element.text());
element.text(val.obfuscated);
});
}
}
)]};
我的问题是:如何使用val.original ?!如果将字段替换为obfuscator.obfuscate()
返回的对象,如何将我的字段用控制器中的“敏感”修饰,以便将field.original发送到后端服务器?以及如何告诉视图在ng-model="field"
中使用“ field.obfuscated”而不是“ field”?
app.factory('obfuscator', function() {
return {
obfuscate: obfuscate
};
function obfuscate(value) {
if (value) {
let val = value.toString(); // now can be called on numbers too...
let len = val.length;
let chunk = Math.floor(len / 3);
let masked = len - (chunk * 2);
return val.substr(0, chunk) + "*".repeat(masked) + val.substr(len - chunk, chunk);
}
return value;
}
}).directive('sensitive', ['obfuscator', function(obfuscator) {
// directive for
return {
restrict: 'A',
priority: 1,
link: function(scope, element, attrs) {
attrs.$observe('ngBind', function() {
element.text(obfuscator.obfuscate(element.text()));
});
}
}
}]).directive('obfuscated', ['obfuscator', function(obfuscator) {
return {
restrict: 'A',
priority: 1,
require: 'ngModel',
link: function(scope, element, attrs, controller) {
controller.$formatters.push((value) => obfuscator.obfuscate(value));
controller.$parsers.shift((value) => {
element.text(obfuscator.obfuscate(value));
return value;
});
}
}
}]);