我想要实现的行为是一个数字文本框,未聚焦时显示 2 个小数位,聚焦时显示每个小数位。与此问题中的行为相同:
ko.extenders.digitInput = function(target, option) {
var realValue = target,
showRealValue = ko.observable(false),
displayValue = ko.computed({
read: function() {
return showRealValue()
? realValue()
: parseFloat(realValue()).toFixed(2);
},
write: realValue
}, this);
displayValue.showRealValue = showRealValue;
return displayValue;
};
var ViewModel = function() {
this.value1 = ko.observable(6.452345).extend({ digitInput: true });
this.value2 = ko.observable(4.145).extend({ digitInput: true });
};
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input data-bind="value: value1, hasFocus: value1.showRealValue" type="number"/>
<input data-bind="value: value2, hasFocus: value2.showRealValue" type="number"/>
但是现在我想使用AngularJS
而不是Knockoutjs
.我对这个框架真的很陌生,所以我不知道正确的方法是使用服务、工厂还是只是使用 ng-blur
和 ng-focus
在主控制器上调用通用事件。我也在使用打字稿。提前谢谢。
我在打字稿中找到了一个可行的解决方案:
interface INumericTextBox extends angular.IDirective {
}
interface INumericTextBoxScope extends angular.IScope {
}
interface INumericTextBoxAttributes extends angular.IAttributes {
ngModel: string
}
interface IElement extends angular.IAugmentedJQuery {
value: string
}
NumericTextBox.$inject = ["$window"];
function NumericTextBox($window: angular.IWindowService): INumericTextBox {
// Usage:
// <numeric-textbox></numeric-textbox>
// Creates:
//
return {
restrict: "A",
link: link
}
function link(scope: INumericTextBoxScope, element, attrs: INumericTextBoxAttributes, ngModelController) {
var realValue;
element.bind('focus', function (scope) {
if (realValue != null) this.value = realValue;
})
element.bind('blur', function (scope) {
realValue = this.value;
this.value = parseFloat(this.value).toFixed(2);
})
ngModelController.$formatters.push(function (data: number) {
//convert data from model format to view format
if (data != null) {
realValue = data;
data = parseFloat(data.toFixed(2));
}
return data; //converted
});
}
}
angular.module("app").directive("numericTextbox", NumericTextBox);
在这里工作JavaScript示例:plnkr