brynner
1/21/2015 - 5:25 PM

Angular directive to force lowercase letters on an input textbox as you type

Angular directive to force lowercase letters on an input textbox as you type

'use strict';

/**
 * @ngdoc directive
 * @name myapp.directive:forceLowerCase
 * @description
 * # forceLowerCase
 */
angular.module('myapp')
  .directive('forceLowerCase', function ($parse) {
    return {
      require: 'ngModel',
      link: function postLink(scope, element, attrs, modelCtrl) {
        var lowerize = function(inputValue) {
          if (!inputValue) { return inputValue; }
          var lowerized = inputValue.toLowerCase();
          if(lowerized !== inputValue) {
            modelCtrl.$setViewValue(lowerized);
            modelCtrl.$render();
          }         
          return lowerized;
        };

        var model = $parse(attrs.ngModel);
        modelCtrl.$parsers.push(lowerize);
        lowerize(model(scope));
      }
    };
  });