How to create a directive in AngularJs that creates a mask and did not modify the ng-model?

1

I created a directive where it serves as a mask for checking account, so when I type a value, always the rightmost value in the input is the digit of my account, until then beauty is working. The problem is that I do not want to change the value of my ng-model if I inform for example 123456 should appear in my view 12345-6 and my ng-model should only be 123456 (without the trace). What is happening and that my ng-model is being changed (12345-6). Does anyone know how to solve this ??

My view is correct, the policy caters to me

NOTE: In the bottom left corner look at my ng-model

angular.module('app').directive('contaCorrenteMask', function () {
    return {
        restrict: 'A',
        require: "ngModel",
        link: function (scope, element, attrs, ctrl) {           

            var _formatContaBanco = function (data) {

                if (!data)
                    return data;

                if (data.length == 1)
                    return data;

                data = data.replace(/[^0-9]+/g, "");

                var digito = data.slice(-1);
                var conta = data.slice(0, -1);
              
                return conta + '-' + digito;
            };
           
            // Send out changes from inside: 
            scope.$watch(attrs.ngModel, function (val) {
                scope.model = val;
                ctrl.$setViewValue(_formatContaBanco(scope.model));
                ctrl.$render();
            });
        }
    };
})
    
asked by anonymous 19.04.2018 / 19:16

1 answer

0

Then your problem is that you are using setViewValue .

ctrl.$setViewValue(_formatContaBanco(scope.model));

This causes ngModel to also be updated to have different viewValue and different modelValue

Format the ngModel text for the view

ngModel.$formatters.push(function(value) {
   return value.toUpperCase();
});

Formats the view text for ngModel

ngModel.$parsers.push(function(value) {
   return value.toLowerCase();
});

Now your corrected code

angular.module('app').directive('contaCorrenteMask', function () {
    return {
        restrict: 'A',
        require: "ngModel",
        link: function (scope, element, attrs, ctrl) {           

            var _formatContaBanco = function (data) {

                if (!data)
                    return data;

                if (data.length == 1)
                    return data;

                data = data.replace(/[^0-9]+/g, "");

                var digito = data.slice(-1);
                var conta = data.slice(0, -1);

                return conta + '-' + digito;
            };

            // Send out changes from inside: 
            ctrl.$formatters.push(function (modelValue) {
                return _formatContaBanco(modelValue);
            });
        }
    };
})
    
19.04.2018 / 23:08