gpt4 book ai didi

javascript - $viewValue 未应用于文本框指令?

转载 作者:行者123 更新时间:2023-11-27 22:47:54 25 4
gpt4 key购买 nike

尝试创建 mask
控制台打印 $viewValue 不同但不适用于 View 。

NgModelController {$viewValue: "656-56", $modelValue: "656565", $$rawModelValue: "656565", $validators: Object, $asyncValidators: Object…}

代码:

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 链接

最佳答案

基本上,您不应该在使用 textbox 指令的同一元素上应用 angular-mask 指令。因为如果您将其放置在 textbox 模型的 ngModel 上,而不是内部 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}}

Demo Fiddle

关于javascript - $viewValue 未应用于文本框指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38280115/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com