Reputation: 3317
Hi! I have the following input box :
<div ng-repeat="item in items"
<input ng-model="item.cost" />
</div>
I am trying to figure out how to apply "currency" filter to the input box. So that when value is displayed it displays with $ sign and proper currency notations. I can do with span using {{item.cost | currency }}
but I need the box to be editable to change the value if needed.
Please let me know how I can apply currency filter to the input box.
Thanks
Upvotes: 1
Views: 2074
Reputation: 909
Try this
.directive('currencyFormatter', ['$filter', function ($filter) {
formatter = function (num) {
return $filter('currency')(num);
};
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attr, ngModel) {
ngModel.$parsers.push(function (str) {
return str ? Number(str) : '';
});
ngModel.$formatters.push(formatter);
element.bind('blur', function() {
element.val(formatter(ngModel.$modelValue))
});
element.bind('focus', function () {
element.val(ngModel.$modelValue);
});
}
};
}]);
And the html
<div ng-repeat="item in items">
<input ng-model="item.cost" currency-formatter/>
</div>
<div ng-repeat="item in items">
{{item.cost}}
</div>
Upvotes: 2