angularjs - Angular directive for displaying cents as dollars in an input -


so, have make input currency stores value integer in cents. have directive works, not quite. following directive converts data model view , after being changed, strips extraneous what's going model. problem not update view again when model changes. so, if input showing $10.00 , type in $10.00a, model correctly show 1000, remains in input field.

return {   require: 'ngmodel',   link: function (elem, $scope, attrs, ngmodel) {     ngmodel.$formatters.push(function (val) {       return '$' + (val / 100).tofixed(2);     });     ngmodel.$parsers.push(function (val) {       var replaced = val.replace(/[^\d\.]/g, '');       var split = replaced.split('.');       var merged = split[0] + split[1].slice(0, 2)       return number(merged);     });   } } 

in order update viewvalue need call these 2 functions in newly pushed parser:

//update $viewvalue ngmodel.$setviewvalue(displayedvalue); //reflect on dom element ngmodel.$render(); 

so directive like:

.directive('myfilter', [     function() {             return {             require: 'ngmodel',                 link: function (elem, $scope, attrs, ngmodel) {                     ngmodel.$formatters.push(function (val) {                         return '$' + (val / 100).tofixed(2);                     });                     ngmodel.$parsers.push(function (val) {                         //make sure val string                         val = val.tostring();                         //filter value displaying, keep '$'                         var displayedvalue = val.replace(/[^\d\.\$]/g, '');                         var replaced = val.replace(/[^\d\.]/g, '');                         var split = replaced.split('.');                         var merged = split[0] + split[1].slice(0, 2);                         var typeconverted = number(merged);                         //update $viewvalue           ngmodel.$setviewvalue(displayedvalue);           //reflect on dom element           ngmodel.$render();                         return typeconverted;                     });                 }             }         } ]) 

and working fiddle here : fiddle_link

and similar overstack post has more explanation reason why 2 lines need : https://stackoverflow.com/a/36653378/1300334

hope can you.


Comments

Popular posts from this blog

html - Styling progress bar with inline style -

java - Oracle Sql developer error: could not install some modules -

How to use autoclose brackets in Jupyter notebook? -