Skip to content

Instantly share code, notes, and snippets.

@fpinzn
Created February 17, 2015 02:46
Show Gist options
  • Save fpinzn/03191e775c5666b67370 to your computer and use it in GitHub Desktop.
Save fpinzn/03191e775c5666b67370 to your computer and use it in GitHub Desktop.
currency directive to prepend a $ signto the value and add . every three digits. The model value stays without these ornaments.
module.directive('currency', function () {
return {
require: 'ngModel',
link: function(elem, $scope, attrs, ngModel){
$scope.addPoints = function(val){
console.log("formater points", val);
var count = 0, result;
return _.reduceRight(val, function(memo, item){
if(count % 3 === 0 && count > 0){
result = item + "." + memo
}
else{
result = item + memo;
}
count++;
console.log(result);
return result;
},"")
};
$scope.addDollarSign = function(val){
console.log("formater dollar", val);
return '$' + val;
};
/*
Formatters are called when the ngModel value is changed from inside the code, not through UI interaction.
*/
ngModel.$formatters.push($scope.addPoints);
ngModel.$formatters.push($scope.addDollarSign);
/*
Parsers are called to extract the actual ngModel value from the inmput of the user.
*/
//Remove format points
ngModel.$parsers.push(function(val){
return val.replace(/\./g, '');
});
//Remove dollar sign
ngModel.$parsers.push(function(val){
return val.replace(/^\$/, '');
});
ngModel.$viewChangeListeners.push(function(){
//use the formatters with the modelValue
ngModel.$setViewValue($scope.addDollarSign($scope.addPoints(ngModel.$modelValue)), 'format currency');
//render the value in the ui
ngModel.$render();
})
}
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment