下面是一個完整的指令,它將解析,格式化並對輸入執行角驗證。 (測試對角1.2 & 1.3。)
我們使用這種方式,以便我們的數據模型可以用十進制表示法(0.7634)表示,但我們爲用戶提供了一種可讀的格式(76.34),並執行最大精度。請注意,該指令純粹涉及數字方面。我發現將模板中的'%'單獨插入到模板中更容易,而不是將其包括在此處。
它默認強制執行從-100到100的輸入值,但您可以使用attrs pct-min
和pct-max
提供自己的界限。
'use strict';
angular.module('XLDirectives')
.directive('xlPercentage', function($filter) {
// A directive for both formatting and properly validating a percentage value.
// Assumes that our internal model is expressed as floats -1 to +1: .099 is 9.9%
// Formats display into percents 1-100, and parses user inputs down to the model.
// Parses user input as floats between 0 and 100 into floats less than 1.
// Validates user input to be within the range -100 to +100.
// Sets Angular $valid property accordingly on the ngModelController.
// If a `pct-max` or `pct-min` attribute is specified on the <input>, will use those bounds instead.
// If a `pct-decimals` attr present, will truncate inputs accordingly.
function outputFormatter(modelValue, decimals) {
var length = decimals || 2;
if (modelValue != null) {
return $filter('number')(parseFloat(modelValue) * 100, length);
} else {
return undefined;
}
};
function inputParser(viewValue, decimals) {
var length = decimals || 4;
if (viewValue != null) {
return $filter('number')(parseFloat(viewValue)/100, length);
} else {
return undefined;
}
}
function isWithinBounds(value, upper, lower) {
if (value >= lower && value <= upper) {
return true;
} else {
return false;
}
}
return {
restrict: 'A',
require: 'ngModel',
link: function postLink(scope, element, attrs, ctrl) {
ctrl.$parsers.unshift(function(viewValue) {
// confirm the input from the view contains numbers, before parsing
var numericStatus = viewValue.match(/(\d+)/),
min = parseFloat(attrs.pctMin) || -100,
max = parseFloat(attrs.pctMax) || 100,
decimals = parseFloat(attrs.pctDecimals) || 4,
bounded = isWithinBounds(viewValue, max, min);
if (numericStatus !== null && bounded) {
ctrl.$setValidity('percentage', true);
// round to max four digits after decimal
return inputParser(viewValue, decimals);
} else {
ctrl.$setValidity('percentage', false);
return undefined
}
});
ctrl.$formatters.unshift(outputFormatter);
// we have to watch for changes, and run the formatter again afterwards
element.on('change', function(e) {
var element = e.target;
element.value = outputFormatter(ctrl.$modelValue, 2);
});
}
};
});
// REFS:
// http://stackoverflow.com/questions/17344828/angularjs-should-i-use-a-filter-to-convert-integer-values-into-percentages
// http://stackoverflow.com/questions/13668440/how-to-make-a-percent-formatted-input-work-on-latest-angularjs
來源
2014-10-30 02:54:10
XML
謝謝!關於第二次查詢,我正在尋找貨幣的輸入,即當鍵入輸入時,控件會自動輸入逗號(s)。也許我會從完成貨幣輸入的百分比開始。非常感謝! – Hao
也許值得注意的是,如果一個位於另一個語言環境中,另一個格式化程序/解析器可以使另一個格式化程序要求的模型爲'undefined'(即:$ filter('number')'returns'「4,00'''一個''。「'小數點分隔符)。 – elbaid
這是應該返回一個字符串,而不是一個十進制數?我怎麼能得到它返回一個小數? –