AngularJS: Should I use a filter to convert integer values into percentages?

余生长醉 提交于 2020-01-01 08:35:08

问题


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

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?


回答1:


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.




回答2:


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.

This is an example of a filter: 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.



来源:https://stackoverflow.com/questions/17344828/angularjs-should-i-use-a-filter-to-convert-integer-values-into-percentages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!