erp erp - 2 months ago 22
AngularJS Question

Display input as precentage

I have a html slider and an input field that sits right next to it. The input field displays the same value as the slider .01 - .99. I am wondering how to display the number in the input field as a percentage version of it, ie .99 is displayed as 99%. The code is simple but here:

<div sc-slider
ng-model="vm.baseline"
min="0.01"
max="0.99"
step="0.01"></div>
<input type="text"
class="form-control"
ng-model="vm.baseline"></input>


If you can link me to something else on line cool but I looked and couldn't find anything and surely can't be the only person needing to do this. I tried to do like
vm.baseline *100
but for obvious reasons that didn't work. Help if you can!

Answer

You can implement custom directive that require: ngModel and change input/output with $parsers | $formatters https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

Here is a plunker: https://plnkr.co/edit/FGuskyRwXCScPd1Kpd6a?p=preview

app.directive('toPercent', function(){
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModelCtrl){
      ngModelCtrl.$formatters.push(function(value){
          return value * 100 + '%';
      });

      ngModelCtrl.$parsers.push(function(value){
          return parseFloat(value.replace('%', ''));
      });
    }
  };
});
Comments