我非常新的angularJs我的問題是:AngularJS:輸入類型=數字」解析ngModel字符串值數和背部
我的模型數據都保存在一個數據庫中,如果一個項目被重新打開該數據是顯示隨着保存數據在數據庫中重新保存我與 顯示數字,因爲值存儲爲一個字符串,並且必須被解析到一個整數的問題
下面是HTML:。
<numeric-input numericbinding="item.showInt" ng-model="item.operandvalue" ></numeric-input>
根據t的格式他的項值(bool,int,string),操作數值以不同的方式顯示。這是以數值綁定的值爲導向的。
我試着用下面的指令來分析字符串爲int:
.directive('numericInput', function() {
return {
restrict: 'E',
require: 'ngModel',
scope: {
model: '=ngModel',
numericbinding: '='
},
template: '<input id="integerType" type="number" ng-model="intValue" ng-hide="!numericbinding" >',
link: function (scope) {
//avoid that string and bool is parsed, showInt is false
if (scope.numericbinding === false || scope.numericbinding === undefined) {
return;
}
scope.intValue = parseInt(scope.model, 10);
}
};
})
這種方式是否正確顯示的號碼。但是,如果我想再次存儲我的數據綁定item.operandvalue我在後端得到一個Nullpointer。我知道我需要將數字轉換回字符串。我嘗試了多種方式,例如。
- ng-change:但它從來沒有得到給定的函數。
然後我想在AngularJS - Formatting ng-model before template is rendered in custom directive
.directive('numericInput', function() {
return {
restrict: 'E',
require: 'ngModel',
scope: {
model: '=ngModel',
numericbinding: '='
},
template: '<input id="integerType" type="number" ng-model="item.operandvalue" ng-hide="!numericbinding" >',
link: function (scope, ngModelController) {
//avoid that string and bool is parsed, showInt is false
if (scope.numericbinding === false || scope.numericbinding === undefined) {
//console.log('not a number - return');
return;
}
ngModelController.$formatters.unshift(function(valueFromModel) {
return parseInt(valueFromModel, 10);
});
ngModelController.$parsers.push(function(valueFromInput) {
return valueFromInput.toString();
});
}
};
})
描述然而,valueFromModel是未定義使用ngModelController與格式化器和解析器。該號碼根本不顯示。另外scope.item.operandvalue是未定義的。在Chrome中,錯誤是:TypeError:無法讀取未定義的屬性'operandvalue'。
我認爲我應該將item.operandvalue(數據綁定)保存爲一個字符串並以不同的名稱顯示int值。在我的第一種方式看來,item.operandvalue得到一個數字,數據綁定不再工作。
我該如何解決我的問題?非常感謝您的幫助!