Angular: Empty Fiddle
http://angularjs.org/
HTML
<form ng-app="myApp" ng-controller="MyCtrl">
<div >
<input type="text" ng-model="amount" format="currency" val = "amount">
<br>
formatted Soles value : <span>{{amount | currency}}</span><br>
ng-model : <span>{{amount}}</span>
</div>
<button ng-click="onSubmit()"> Save Soles</button>
<br><br><br>
<div >
<input type="text" ng-model="amountD" format="currency" symbol="$" val = "amountD">
<br>
formatted Dollar value : <span>{{amountD | currency : '$'}}</span><br>
ng-model dollar : <span>{{amountD}}</span>
</div>
<button ng-click="onSubmitD()"> Save Dollar</button>
</form>
CSS
</style>
<script src="//code.angularjs.org/1.5.4/angular.min.js"></script>
<script src="//code.angularjs.org/1.5.4/i18n/angular-locale_es-pe.js"></script>
<style>
JavaScript
angular.module('myApp', []);
angular
.module('myApp').directive('format', ['$filter', function ($filter) {
return {
require: 'ngModel',
scope: {
val : '=val'
},
link: function (scope, elem, attrs, ctrl) {
if (!ctrl) return;
ctrl.$formatters.unshift(function (a) {
if(attrs.symbol == '$')
return $filter(attrs.format)(ctrl.$modelValue, '$')
else
return $filter(attrs.format)(ctrl.$modelValue)
});
elem.bind('blur', function(event) {
var a = elem.val();
var plainNumber = a.split('.').filter(function(e){
return (e.length > 0);
}).join('.');
var i = 0;
if(isNaN(parseFloat(plainNumber))){
i = (attrs.symbol == '$') ? 1 : 3;
}
var num = plainNumber.substring(i, plainNumber.length).replace(/,/g,'');
if(attrs.symbol == '$')
elem.val($filter('currency')(num, attrs.symbol));
else
elem.val($filter('currency')(num));
var n =parseFloat(num);
scope.val = Number(n);
if(!scope.$$phase) {
scope.$apply();
}
});
}
};
// controller
}]).controller('MyCtrl', ['$scope', function($scope) {
$scope.amount = 99;
$scope.amountD = 77;
$scope.onSubmit = function() {
console.log($scope.amount);
console.log(typeof $scope.amount);
}
$scope.onSubmitD = function() {
console.log($scope.amountD);
console.log(typeof $scope.amountD);
}
}]);