AngularJS 新手。试图弄清楚我将如何实现这一目标,或者是否可能实现。
我知道我可以使用
将值绑定(bind)到输入框<input type="number" ng-model="myvalue">
但是如果我想要模型和 View 之间的值发生转换怎么办?
例如,对于货币,我喜欢以美分存储我的值(value)。但是,我想允许我的用户输入美元金额。因此,我需要在 View 和 Controller 之间将值转换为 100 倍,即在模型中我将有 100,在 View 中我将有 1。
这可能吗?如果是这样,我怎样才能实现这一目标?
最佳答案
我遇到了和你一样的问题。我开始使用 wciu 的解决方案,但遇到了一个问题,即值会在美分和美元之间闪烁。我最终连接到了用于在 View 和模型之间进行绑定(bind)的管道。
merchantApp.directive('transformTest', function() {
return { restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
if(ngModel) { // Don't do anything unless we have a model
ngModel.$parsers.push(function (value) {
return value*100;
});
ngModel.$formatters.push(function (value) {
return value/100;
});
}
}
};
});
关于angularjs - 是否可以在 AngularJS 中转换 View 和模型之间的值以进行输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13420693/