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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With