[英]JavaScript function return html object, how can I parse it?
我有一個AngularJS(1.4)應用程序,並且試圖通過指令操縱輸入type =“ number”。 我必須使用type =“ number”,因為在iOs上使用type =“ tel”時,字符是“。”。 沒有出現在鍵盤上,因此無法插入小數位數。
目的是使用戶在“。”之前最多插入3位數字。 最多2位數字。 點數不得超過一。 那就是我想要在輸入字段中使用的格式。 問題是,如果我通過,則在指令中打印變量this.value,它不包含任何“。”。
這是html代碼:
<input required type='number' limit-to-number="3" number-of-decimals="2" ng-required="true" ng-model="invoice.price">
這是指令:
directive("limitToNumber", [function() {
return {
restrict: "A",
link: function(scope, elem, attrs) {
var limit = parseInt(attrs.limitToNumber);
var number_of_decimals = parseInt(attrs.numberOfDecimals);
var digit_array = [];
angular.element(elem).on("keydown", function(e) {
console.log(this);
});
}
};
}]).
我嘗試了不同的方法,主要問題是this.value不包含“。”。 例如,如果表單中的輸入為“ 12”:
console.log(this.value) // -> 12
但是,如果表單中的輸入為“ ...... 12 .....”:
console.log(this.value) // -> "" empty string
但是我注意到只打印“ this”會返回輸入的整個html:
<input required type='number' limit-to-number="3" number-of-decimals="2" ng-required="true" ng-model="invoice.price" name="price" aria-invalid="false">
#shadow-root (user-agent)
<div id="text-field-container" pseudo="-webkit-textfield-decoration-container">
<div id="editing-view-port">
<div id="inner-editor">12.</div>
...
在具有id =“ inner-editor”的div中,我可以看到輸入字段的確切值。 現在的問題是,這不起作用:
console.log(this.findElementById("inner-editor")); // -> Uncaught TypeError: this.getElementById is not a function
如何從對象“ this”中提取該div值?
</ s> </ s> </ s>
您可以使用
<input type="number" step="0.01" max="999.99" min="0" required />
當然,您必須在提交后驗證用戶的輸入(角度表單驗證示例)。
嘗試這個:
.directive('limitToNumber', function () {
return {
restrict: 'A',
require: '?ngModel',
link: function (scope, element, attrs, modelCtrl) {
modelCtrl.$parsers.push(function (inputValue) {
// inputValue variable will contain the input box value
var limit = parseInt(attrs.limitToNumber);
var number_of_decimals = parseInt(attrs.numberOfDecimals);
var digit_array = [];
if (inputValue == undefined) return '';
// Your transformation code will be written here
// Assign the transformed value to transformedInput variable
var transformedInput = '';
if (transformedInput !== inputValue) {
// This will update the input box
modelCtrl.$setViewValue(transformedInput);
modelCtrl.$render();
}
return transformedInput;
});
}
};
});
請讓我知道是否有幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.