How to use $parsers and $formatters in a custom directive to force an input to lowercase
| angular.module('yourModule').directive('lowercase', function() { | |
| return { | |
| require: 'ngModel', | |
| restrict: 'AEC', | |
| link: function(scope, element, attrs, ngModelCtrl) { | |
| // For the parser, we also need to make sure we re-update the DOM with the transformed value. | |
| ngModelCtrl.$parsers.push(function(val) { | |
| var newVal = angular.lowercase(val); | |
| if (newVal !== val) { | |
| ngModelCtr.$setViewValue(newVal); | |
| ngModelCtrl.$render(); | |
| } | |
| return newVal; | |
| }); | |
| // shortcut to get it done for $formatters, since the transformation is | |
| // all we need here, since data going through $formatters is already on | |
| // its way to the DOM from the model end. | |
| ngModelCtrl.$formatters.push(angular.lowercase); | |
| } | |
| }; | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment