尝试创建屏蔽
控制台打印$ viewValue不同但在视图中不适用。
NgModelController {$ viewValue:“656-56”,$ modelValue:“656565”, $$ rawModelValue:“656565”,$ validators:Object,$ asyncValidators: 对象...}
代码:
var app = angular.module("masking",[]);
app.directive('textbox', function mask() {
return {
restrict: 'E',
transclude: true,
require: 'ngModel',
scope: { },
bindToController: {
model: "=ngModel",
},
controller: function($scope, $attrs) {
},
compile: function() {
return {
pre: function(scope, el, attrs) {
},
post: function(scope, element, attrs, Ctrls) {
}
};
},
template: '<div><input type="text" ng-model="Ctrl.model" /> </div> ',
controllerAs: 'Ctrl',
};
});
app.directive('angularMask', function () {
return {
restrict: 'A',
require: 'ngModel',
scope: false,
link: function ($scope, el, attrs, model) {
$scope.$watch(function(){return attrs.angularMask;}, function(value) {
if (model.$viewValue != null){
model.$viewValue = mask(String(model.$viewValue).replace(/\D/g, ''));
el.val(model.$viewValue);
}
});
model.$formatters.push(function (value) {
return value === null ? '' : mask(String(value).replace(/\D/g, ''));
});
model.$parsers.push(function (value) {
model.$viewValue = mask(value);
var modelValue = attrs.isModelValueEqualViewValues ? model.$viewValue : String(value).replace(/\D/g, '');
el.val(model.$viewValue);
return modelValue;
});
function mask(val) {
console.log(model);
var format = attrs.angularMask,
arrFormat = format.split('|');
if (arrFormat.length > 1) {
arrFormat.sort(function (a, b) {
return a.length - b.length;
});
}
if (val === null || val == '') {
return '';
}
var value = String(val).replace(/\D/g, '');
if (arrFormat.length > 1) {
for (var a in arrFormat) {
if (value.replace(/\D/g, '').length <= arrFormat[a].replace(/\D/g, '').length) {
format = arrFormat[a];
break;
}
}
}
var newValue = '';
for (var nmI = 0, mI = 0; mI < format.length;) {
if (!value[nmI]) {
break;
}
if (format[mI].match(/\D/)) {
newValue += format[mI];
} else {
newValue += value[nmI];
nmI++;
}
mI++;
}
return newValue;
}
}
};
});
HTML代码
<textbox ng-model="myModelPhone" angular-mask="000-000-000"></textbox>
{{myModelPhone}}
https://jsfiddle.net/amitme/s0Lenp0w/1/这里是jsfiddle链接
答案 0 :(得分:1)
基本上,您不应该在使用angular-mask
指令的同一元素上应用textbox
指令。因为如果您将其放在ngModel
模型的textbox
而不是内部ngModelController
上。
您需要更改指令结构。来自textbox
指令只需在masking-pattern="000-000-000"
然后将指令模板更改为
template: function(element, attrs){
return '<div><input type="text" ng-model="Ctrl.model" angular-mask="'+attrs.maskingPattern+'"/> </div> '
}
<强> HTML 强>
Text box directive : <textbox ng-model="myModelPhone" masking-pattern="000-000-000"></textbox>
{{myModelPhone}}