【发布时间】:2014-03-24 15:21:53
【问题描述】:
我对 angularJs 很陌生。我的问题是:
我的模型数据保存在数据库中,如果重新打开项目,则会显示数据。通过保存,数据再次存储在数据库中。我在显示号码时遇到问题 因为该值存储为字符串,并且必须解析为整数。
这里是html:
<numeric-input numericbinding="item.showInt" ng-model="item.operandvalue" ></numeric-input>
根据项目值的格式(bool、int、string),操作数值以不同的方式显示。这与 numericbinding 的值有关。
我尝试使用以下指令将字符串解析为 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:但它从未进入给定的函数中。
然后我想使用带有格式化程序和解析器的 ngModelController,如 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 是未定义的。号码根本不显示。 scope.item.operandvalue 也是未定义的。在 Chrome 中,错误是:TypeError: Cannot read property 'operandvalue' of undefined.
我认为我应该将数据绑定的 item.operandvalue 保留为字符串,并以不同的名称显示 int 值。在我的第一种方式中,item.operandvalue 似乎获得了一个数字,并且数据绑定不再起作用。
如何解决我的问题?非常感谢您的帮助!
【问题讨论】:
标签: javascript angularjs