Reputation: 95
All I want to do is have the numbers I type automatically formatted to $ as I type it in the input but keep the actual model as number only without the $. I tried it different ways but all I have now is if I have some value already in the model (instead of null) it'll show with $ . But if it's null or if I delete everything inside the input and start from scratch then the values are not being formatted as $ . What am I doing wrong? Here's a jsfiddle
http://jsfiddle.net/rmzqomzz/1/
angular.module('HelloApp', []);
function myTest() {
return {
restrict: 'EA',
require: 'ngModel',
link: function(scope, element, iAttrs, ngModel) {
console.log(iAttrs.myTest);
ngModel.$formatters.push(function(modelValue){
if(!modelValue) return;
if(iAttrs.myTest == 'money'){
return '$ '+modelValue;
}else{
return modelValue +' %';
}
});
ngModel.$parsers.push(function(viewValue){
return viewValue.replace('$', '').trim();
});
scope.$watch(
function(){
return ngModel.$modelValue;
}, function(newValue, oldValue){
console.log('value changed '+ newValue);
}, true
);
}
};
};
angular.module('HelloApp').directive('myTest', myTest);
angular.module('HelloApp').controller('HelloController', function($scope) {
$scope.mon = {'balu':null};
});
Thanks
Upvotes: 0
Views: 370
Reputation: 343
Have you tried using a filter?
<input ng-model="num">
<p>Value {{num | currency:"$"}}</p>
</body>
https://docs.angularjs.org/api/ng/filter/currency
Upvotes: 1