Steven Scott
Steven Scott

Reputation: 11250

AngularJS Enter a Formatted value similar to a filter and remove formatting for processing

I have a filter for showing currency values that extended the default currency filter. Our API will store data in cents, but I want the User Interface to show the price similar to how people are use to working with it (dollars and cents).

The filter is straight forward, and works on normal fields, ui.Grid, etc...

/**
 * Currency Filter
 */
angular.module('myApp').filter('SLS_Currency', function($filter) {
    var CurrencyFilter = $filter('currency');
    return function(Input){
        return CurrencyFilter(Input / 100);
    };
});

This converts the number to Dollars and Cents (123 becomes $1.23). However, my problem is now using this on a form in the input field. I want to be able to still control error checking, etc..., and want the field to display as $1.23, but when editing allow the user to type a value with or without formatting?

I am looking to be able re-use this filter, not necessarily create another piece of code to do the same thing. I have seen suggestions with $watch, but it appears a larger form would have a number of these, and then there would be a directive for input, and a filter for viewing. Is it possible to do within the filter, or to use the directive everywhere, including ui.Grid?

<form>
    <div class="form-group">
        <label>Unit Price</label>
        <input type="text" placeholder="Unit Price (cents)" ng-model="storeitem.UnitPrice | SLS_Currency" class="form-control" />
    </div>

    <div class="form-group">
        <label>Quantity</label>
        <input type="text" placeholder="Quantity (1-99)" ng-model="storeitem.nForQuantity" class="form-control" />
    </div>
</form>

Upvotes: 0

Views: 704

Answers (1)

HankScorpio
HankScorpio

Reputation: 3651

It would be best to use a directive to do this. You can use your filter within the directive if you want.

angular.module('slsCurrency.directive', []).directive('slsCurrency', 
    function($filter) {
      return {
        restrict: 'A',
        require: '^ngModel',
        link: function($scope, element, attrs, ngModelController) {
            var slsCurrencyFilter = $filter('SLS_Currency');

            ngModel.$formatters.push(function(value){
                return slsCurrencyFilter(value);
            });

            ngModel.$parsers.push(function(value){
                // Insert code here to detect formatting (e.g. $), strip out what you don't need, then return it.
                // This is the value that will be saved to your DB
                return value;
            });
        }
      };
    }
  );

-

    <input type="text" sls-currency placeholder="Unit Price (cents)" ng-model="storeitem.UnitPrice" class="form-control" />

Upvotes: 1

Related Questions