是否可以在AngularJS中的视图和模型之间转换值以进行输入? [英] Is it possible to transform a value between view and model in AngularJS for input?
问题描述
AngularJS的新功能.试图弄清楚我将如何完成此任务,或者是否有可能.
New to AngularJS. Trying to figure out how I would accomplish this, or if it is possible at all.
我知道我可以使用
<input type="number" ng-model="myvalue">
但是,如果我希望模型和视图之间的值被转换,该怎么办?
But what if I want it such that the value between the model and the view is transformed?
例如,对于货币,我喜欢以美分存储我的价值.但是,我想允许我的用户输入美元金额.因此,我需要在视图和控制器之间将值转换为100倍,即在模型中,我将拥有100,在视图中,我将拥有1.
For example, for currency, I like to store my value in cents. However, I want to allow my users to enter dollar amounts. So I need to convert the value by a factor of 100 between the view and controller, i.e. in the model I would have 100, and in the view, I would have 1.
有可能吗?如果是这样,我该如何实现?
Is that possible? If so, how can I achieve that?
推荐答案
我遇到了与您相同的问题.我开始使用wciu的解决方案,但遇到一个问题,即价值会在美分和美元之间波动.我最终迷上了用于在视图和模型之间进行绑定的管道.
I ran into the same problem as you. I started using wciu's solution but ran into an issue where the values would flicker between the cents and dollars. I ended up hooking into the pipeline that is used to do the binding between view and model.
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中的视图和模型之间转换值以进行输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!