Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apply currency filter to the input field in angularjs

Hi when I am using span tags I can apply the money filter like

<div ng-repeat="item in items">
    <span>
        {{item.cost | currency}}
    </span>
</div>

I am wondering how I can apply same currency filter in input tag. i.e

<div ng-repeat="item in items">
    <input type="text"  ng-model="item.cost | currency" />
</div>

When I try to apply currency filter to the input field as above it doesnt work. Please let me know how to apply currency filter to input field. Thanks

like image 621
J. Davidson Avatar asked Jul 07 '14 16:07

J. Davidson


3 Answers

I created a simple directive that handles formatting input fields. Here is a jsfiddle example. To use it add this to your existing code.

<div ng-repeate="item in items">
    <input type="text"  ng-model="item.cost" format="currency" />
</div>

And add this directive to your code.

// allow you to format a text input field.
// <input type="text" ng-model="test" format="number" />
// <input type="text" ng-model="test" format="currency" />
.directive('format', ['$filter', function ($filter) {
    return {
        require: '?ngModel',
        link: function (scope, elem, attrs, ctrl) {
            if (!ctrl) return;

            ctrl.$formatters.unshift(function (a) {
                return $filter(attrs.format)(ctrl.$modelValue)
            });

            elem.bind('blur', function(event) {
                var plainNumber = elem.val().replace(/[^\d|\-+|\.+]/g, '');
                elem.val($filter(attrs.format)(plainNumber));
            });
        }
    };
}]);
like image 135
jjbskir Avatar answered Oct 18 '22 21:10

jjbskir


Unfortunately you can not format using ng-model. At least not that way. You will need to create your own directive that implements a parser and formatter. Here is a similar question.

There is a pretty good directive our there that does that currently: ngmodel-format

like image 38
Esteban Felix Avatar answered Oct 18 '22 21:10

Esteban Felix


<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Example - example-example52-production</title>


       <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.14/angular.min.js"></script>



      </head>
      <body ng-app="">
         <script>
    function Ctrl($scope) {
      $scope.amount = 1234.56;
    }
       </script>
      <div ng-controller="Ctrl">
      <input type="number" ng-model="amount"> <br>
      default currency symbol ($): <span id="currency-default">{{amount | currency}}</span>             <br>
      custom currency identifier (USD$): <span>{{amount | currency:"USD$"}}</span>
       </div>
       </body>
      </html>
like image 39
sam rodrigues Avatar answered Oct 18 '22 20:10

sam rodrigues