0

Is there a way to not bind value to model , and ONLY bind it to model when value is valid.

1
  • you could use $validator on ngModel from directive.. Commented Nov 16, 2015 at 6:39

1 Answer 1

1

Use $parsers. The example below restricts input to your model for numbers only. Obviously you can change that to be whatever you require to make your input valid.

angular.module('app').
directive('onlyDigits', function () {

    return {
        restrict: 'A',
        require: '?ngModel',
        link: function (scope, element, attrs, modelCtrl) {
            modelCtrl.$parsers.push(function (inputValue) {
                if (inputValue == undefined) return '';
                var transformedInput = inputValue.replace(/[^0-9]/g, '');
                if (transformedInput !== inputValue) {
                    modelCtrl.$setViewValue(transformedInput);
                    modelCtrl.$render();
                }
                return transformedInput;
            });
        }
    };
});

<input type="text" name="number" only-digits>

Code sample comes from this SO question

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.