【发布时间】:2017-01-18 06:56:29
【问题描述】:
我想在 AngularJs 中用字符分隔符格式化文本框中输入的数字。
我创建了一个指令来进行格式化。该指令正在生成正确的输出,但无法正确更新 ngModel。
<input type="text" data-ng-model="aadhaar" dashsep="'-'">
.directive('dashsep', function($timeout) {
'use strict';
return {
restrict: 'A',
scope: {
dashsep: '=',
ngModel: '=ngModel'
},
require: '?ngModel',
link: function(scope, element, attr) {
element.bind("keyup", function (event) {
var formattedAdh = "";
//console.log(element.val());
var test = element.val().toString();
for(var i=0;i<=test.length-1;i++){
//console.log(test[i]);
if(i%4 === 0 && i>0){
formattedAdh+= scope.dashsep;
}
formattedAdh += test[i];
}
// Following script is not updateing the ngModel/textbox with the formatted value properly //
/*
//element.val(scope.$eval(formattedAdh));
// OR
//scope.ngModel = formattedAdh;
*/
// Following output is showing proper value IF ABOVE SCRIPT IS COMMENTED //
console.clear();
console.log(formattedAdh);
});
}
};
});
此Plunker 中提供了完整的脚本。
【问题讨论】:
标签: angularjs-directive angular-ngmodel