javascript AngularJS:我应该使用过滤器将整数值转换为百分比吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17344828/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
AngularJS: Should I use a filter to convert integer values into percentages?
提问by Amit Erandole
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>
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
现在我想要的是使用一个过滤器,它接受用户输入的整数,并通过乘以0.01
或除以将其转换为百分比,然后再将其100
发送到控制器进行计算
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?
这种工作但我不应该为此任务使用过滤器吗?我该怎么做呢?
采纳答案by kfis
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 outthey don't use the filter there, too.
好吧,您只是使用 ctrl.$parser 和 ctrl.$formatter 以绝对正确的方式做到了您可以省略 $filter 的事情,那里绝对不需要它。 只需检查一下,他们也不使用那里的过滤器。
回答by Greg
I think you should use a directive. If you think you are about to fall back to using JQuery to start manipulating the DOM elements then a directive is probably what you want.
我认为您应该使用指令。如果您认为您将回退到使用 JQuery 开始操作 DOM 元素,那么指令可能就是您想要的。
This is an example of a filter: http://embed.plnkr.co/TT6ZwOF6nYXwMcemR3JF/preview
这是一个过滤器的例子:http: //embed.plnkr.co/TT6ZwOF6nYXwMcemR3JF/preview
What you could do is filter the value you enter as part of a watch event. However that depends on your specific use case.
您可以做的是过滤您作为监视事件的一部分输入的值。但是,这取决于您的特定用例。