Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

comma format as typing in angular

In jqxwidget http://www.jqwidgets.com/jquery-widgets-demo/demos/jqxnumberinput/index.htm

by default the comma’s are already in place and separated by underscore.

what i want is to have the field empty and as soon as user starts typing the comma should come as and when similarly to F2 cell render-er.

so when typed 100 is should show 100 when typed 10000 ,it should show 10,000

also i have angular in my app as we are using jqxwidget in conjucation with so any angular way is also fine

one plugin i have found does the job but when focus out not when typing https://www.npmjs.com/package/angular-numeric-directive

like image 632
AutoMEta Avatar asked Oct 09 '15 13:10

AutoMEta


2 Answers

Hey I have solved this before by creating a directive that applies a filter to your HTML input. Here is a jsfiddle example

This is the directive. It both formats the user's input and keeps the cursor where the user is typing. My one issue with this is the logic behind where the cursor should be pointed.

fessmodule.directive('format', ['$filter', function ($filter) {
return {
    require: '?ngModel',
    link: function (scope, elem, attrs, ctrl) {
        if (!ctrl) return;

        var parts = attrs.format.split(':');
        attrs.foramtType = parts[0];
        attrs.pass = parts[1];

        ctrl.$formatters.unshift(function (a) {
            return $filter(attrs.foramtType)(ctrl.$modelValue, attrs.pass)
        });


        ctrl.$parsers.unshift(function (viewValue) {
            var cursorPointer = elem.context.selectionStart;
            var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');
            elem.val($filter(attrs.foramtType)(plainNumber, attrs.pass));
            elem.context.setSelectionRange(cursorPointer, cursorPointer);
            return plainNumber;
        });

    }
};

And the HTML to activate it

<input type="text" ng-model="test" format="number:2" />
like image 107
jjbskir Avatar answered Oct 30 '22 09:10

jjbskir


Angular already provides pretty basic formatting filters like

html : {{val | number:0}}
script: $scope.val = 1234.56789;

ref:

https://docs.angularjs.org/api/ng/filter/number
https://docs.angularjs.org/api/ng/filter/currency
https://scotch.io/tutorials/all-about-the-built-in-angularjs-filters
like image 39
Aishwat Singh Avatar answered Oct 30 '22 09:10

Aishwat Singh