【发布时间】:2014-04-09 21:11:40
【问题描述】:
我正在尝试创建一个指令和过滤器以从输入类型数字中获取数字输入,并在模糊时将其显示为分数(如果适用),然后在焦点上将其显示为小数。模型需要以小数形式存储。
如果字段是文本字段,因为模型是分数,我当前的代码可以工作,但是如果我将其更改为数字字段,它将不允许模型更新,因为字符串不是数字。我还没有制定出模糊/聚焦焦点,但这应该不是这一步的问题。
任何帮助将不胜感激!
到目前为止我的代码如下:
.directive('fractionView', ['$filter', function($filter) {
return {
require: 'ngModel',
link: function(scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function(inputValue) {
var transformedInput = $filter('fraction')(inputValue);
if (transformedInput != inputValue && transformedInput) {
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
}])
.filter('fraction', function() {
return function(input) {
function HCF(u, v) {
var U = u, V = v;
while (true) {
if (!(U %= V))
return V;
if (!(V %= U))
return U;
}
}
return fraction(input);
//convert a decimal into a fraction
function fraction(decimal) {
if (!decimal) {
decimal = this;
}
whole = String(decimal).split('.')[0];
decimal = parseFloat("." + String(decimal).split('.')[1]);
num = "1";
for (z = 0; z < String(decimal).length - 2; z++) {
num += "0";
}
decimal = decimal * num;
num = parseInt(num);
for (z = 2; z < decimal + 1; z++) {
if (decimal % z == 0 && num % z == 0) {
decimal = decimal / z;
num = num / z;
z = 2;
}
}
//if format of fraction is xx/xxx
if (decimal.toString().length == 2 &&
num.toString().length == 3) {
//reduce by removing trailing 0's
decimal = Math.round(Math.round(decimal) / 10);
num = Math.round(Math.round(num) / 10);
}
//if format of fraction is xx/xx
else if (decimal.toString().length == 2 &&
num.toString().length == 2) {
decimal = Math.round(decimal / 10);
num = Math.round(num / 10);
}
//get highest common factor to simplify
var t = HCF(decimal, num);
//return the fraction after simplifying it
if (isNaN((decimal / t)) || isNaN(t)) {
return;
} else {
return ((whole == 0) ? "" : whole + " ") + decimal / t + "/" + num / t;
}
}
}
});
【问题讨论】:
标签: javascript angularjs angularjs-directive angularjs-filter