AngularJS:我应该使用过滤器来整数值转换为百分比? [英] AngularJS: Should I use a filter to convert integer values into percentages?
问题描述
我需要收集变化率 - 百分比 - 从我的应用程序的用户。下面是我使用的输入法:
I need to collect a rate of change - in percentages - from my application's users. Here is the text input I am using:
<label for="annual-change" class="pt-underline"> I am anticipating
<input id="annual-change" ng-model="calc.yrChange" type="text" placeholder="0" /> % of growth annually.<br><br>
</label>
现在我想要的是使用一个过滤器,取整数金额,用户输入并通过 <0.01 / code>或除以<乘以其转换为百分比code> 100
的之前,我将它发送到控制器进行计算的
Now what I want is to use a filter that takes the integer amount that the user inputs and convert it to a percentage by multiplying it by 0.01
or dividing it by 100
before I send it to the controller for calculations
但我就是想不通的地方放置过滤器,以及如何把它捞起来。所以我用像这样一个指令试了一下:
But I just can't figure out where to place the filter and how to hook it. So I tried it with a directive like so:
app.directive("percent", function($filter){
var p = function(viewValue){
console.log(viewValue);
var m = viewValue.match(/^(\d+)/);
if (m !== null)
return $filter('number')(parseFloat(viewValue)/100);
};
var f = function(modelValue){
return $filter('number')(parseFloat(modelValue)*100);
};
return {
require: 'ngModel',
link: function(scope, ele, attr, ctrl){
ctrl.$parsers.unshift(p);
ctrl.$formatters.unshift(f);
}
};
});
这类型的作品,但我不应该使用这个任务过滤器?我该怎么做呢?
This kind of works but shouldn't I be using a filter for this task? How do I do this?
推荐答案
嗯,你只是没有绝对的正确方法与Ctrl键。$解析器和Ctrl键。$格式化
你只是离开了$过滤器的东西,它的absulotuly没有必要存在。
刚检查出来他们不使用过滤器那里。
Well, you just did it the absolute right way with the ctrl.$parser and ctrl.$formatter You just can leave out the $filter thing, its absulotuly not needed there. Just check it out they don't use the filter there, too.
这篇关于AngularJS:我应该使用过滤器来整数值转换为百分比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!