Textarea Maxlength AngularJQuery

A maxlength directive that uses JQuery to get things done.

by ksevksev

HTML

<div class="parent" ng-app="myApp">
    <h1>Textarea Maxlength = 5</h1>
    <h3>Open the console to see the debug information.</h3>
    <label for="text">Type Text In Here</label>:
    <textarea id="text" cols="40" rows="5" my-maxlength="5" ng-model="textareaText"></textarea>
    <br/><br/>
    <div>Completely functional but not truly angular?</div>
    <br/><br/>
    <div>Model Value=<span class="model">[{{textareaText}}]</span></div>
</div>

CSS

</style> <!-- Ugly Hack due to jsFiddle issue: http://goo.gl/BUfGZ --> 
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
<style>
.parent { background-color:tan; }
.model { font-weight:bold; }

JavaScript

(function () {
    'use strict';
    var myAppModule = angular.module('myApp', []);
    myAppModule.controller('MyController', function($scope) {
        $scope.textareaText = true;
    });
	myAppModule.directive('myMaxlength', ['$log', function($log) {
		return {
			restrict: 'A',
			link: function (scope, elem, attrs) {
				var maxlength = parseInt(attrs.myMaxlength, 10);
                $log.info("maxlength=[" + maxlength + "]");
				elem.bind('keydown', function (event) {
                    $log.info("elem.val().length=[" + elem.val().length + "]");

					if (elem.val().length >= maxlength)
					{
						// Void event Except backspace
						if (event.keyCode !== 8){
							event.preventDefault();
						}
					}
				});
			}
		};
	}]);
    
})();