在angularjs中,我正在尝试为货币文本框构建一个指令,该指令从范围内的模型中获取值(金额和货币代码),然后对其应用货币格式。我真的很难使用ngModelController的解析器和格式化程序来构建指令。
首先调用解析器,但未定义modelValue,这意味着尚未从服务器返回数据。那么如何确保在填充模型时调用解析器?同样,我的计算也依赖于db的货币代码,那么如何在解析器中使用这两个值?
我不清楚渲染功能在我的情况下会是什么样子。
这是html:
<numericbox caption="RecurringAmount" controltype="currency" currencycode="{{Model.CurrencyCode}}" value="{{Model.RecurringAmount}}" />
这是指令:
export class NumericTextbox
{
constructor ()
{
var directive: ng.IDirective = {};
directive.restrict = "E";
directive.require = '^ngModel';
directive.replace = true;
directive.template = '<input type="text" />';
directive.scope = true;
directive.link = function ($scope: any, element: JQuerySE, attributes: any, ngModel: ng.INgModelController) {
var injector = angular.element(document.getElementById('app')).injector();
var currencyCacheService: CurrenciesCacheService;
currencyCacheService = injector.get('currenciesCacheService');
var currency = new Currency();
var currencySymbol: string;
ngModel.$formatters.push(function (modelValue) {
if (modelValue) {
var amount: number = modelValue || 0;
var currencyCode: string = attributes.currency || "";
if (currencyCode) {
currency = currencyCacheService.GetItem(currencyCode);
currencySymbol = currency.CurrencySymbol || currency.ISOCurrencyCode;
var formattedNumber = accounting.formatMoney(modelValue,
currencySymbol,
currency.NumberDecimalDigits,
currency.CurrencyGroupSeparator,
currency.CurrencyDecimalSeparator);
return formattedNumber;
}
return modelValue;
}
return 0;
});
ngModel.$parsers.push(function (viewValue: string) {
if (attributes.currenycode) {
var num = viewValue.substring(attributes.currenycode.len, viewValue.length - attributes.currenycode.len);
return num;
}
return viewValue;
});
$scope.$watch(function () {
var amount: any = {};
amount.currencycode = attributes.currencycode;
amount.value = attributes.value;
return amount;
}, function (newVal, oldVal, scope) {
debugger;
if (newVal != oldVal) {
var amount: number = newVal.value || 0;
var currencyCode: string = newVal.currencycode || "";
ngModel.$setViewValue({ num: amount, curr: currencyCode });
}
});
ngModel.$render = function () {
//$scope.value =
console.log(ngModel.$viewValue);
};
}
return directive;
}
}
代码是打字稿。
答案 0 :(得分:0)
如果要更改“显示”值的方式,则需要考虑过滤器而不是指令。像这样:
<div>model.amount|currencyFilter</div>