AngularJS Directive Numeric Format Masking

百般思念 提交于 2019-12-03 22:01:52

Here we used $formatters.unshift and $filter:

JS

var fessmodule = angular.module('myModule', []);

fessmodule.controller('fessCntrl', function ($scope) {
    $scope.test = 123456879;
});
fessmodule.$inject = ['$scope'];

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

            var symbol = "°"; // dummy usage

            ctrl.$formatters.unshift(function (a) {
                return $filter(attrs.format)(ctrl.$modelValue) +  symbol;
            });

            ctrl.$parsers.unshift(function (viewValue) {
                var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');
                elem.val($filter('number')(plainNumber) + symbol);
                return plainNumber;
            });
        }
    };
}]);

HTML

 <input type="text" ng-model="test" format="number"/>

Demo Fiddle

As a side note

You can find this helpful too: Fiddle

The $watch is executed inside a 'digest' loop. The element.bind callback is called from outside angular, so you must add an explicit call to scope.$apply():

element.bind('blur', function() {
    modelCtrl.$setViewValue(setFormatting(element.val(), attrs.symbol));
    modelCtrl.$render();
    scope.$apply();
});

Updated fiddle

See the docs for info about AngularJS's event loop.

You can also use simply

ui-mask="{{'999,999,999°'}}"

I was able to get the ng-model to store values the way I wanted to by adding a modelCtrl.$parsers.push() { ... } to my scope.$watch() { ... }.

scope.$watch(element, function() {
    modelCtrl.$parsers.push(function(inputValue) {
        showAlert("Watch", 1);

        if (!prev) {
            prev = false;
            var returnVal = checkVal(inputValue, modelCtrl, decimals, true, minVal, maxVal);

            if (String(returnVal) === ".") {
                setAndRender(modelCtrl, "");
                return "";
            }
            else {
                return returnVal;
            }
        }
        return String(inputValue).replace(/[^0-9 . -]/g, '');
    });

    prev = true;
    setAndRender(modelCtrl, setFormatting(element.val(), decimals, attrs.prefix, attrs.symbol));
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!