JSFiddle - React, Tailwind, and code Playground
HTML
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<!doctype html>
<html>
<head></head>
<body ng-controller="foo">
<textarea my-maxlength="20" ng-model="bar"></textarea>
<h1>108</h1>
<button ng-click="test()">TEST</button>
</body>
</html>
JavaScript
var myApp = angular.module('myApp', []);
angular.element(document).ready(function() {
angular.bootstrap(document, ['myApp']);
});
function foo($scope) {
$scope.test = function() {
console.log($scope.bar);
}
}
myApp.directive('myMaxlength', ['$compile', function($compile) {
return {
restrict: 'A',
scope: { bar: "=ngModel" },
link: function (scope, element, attrs) {
element = $(element);
scope.charsRemaining = parseInt(attrs.myMaxlength);
scope.onEdit = function() {
var maxLength = parseInt(attrs.myMaxlength),
currentLength = parseInt(element.val().length);
if (currentLength >= maxLength) {
element.val(element.val().substr(0, maxLength));
scope.charsRemaining = 0;
} else {
scope.charsRemaining = maxLength - currentLength;
}
scope.$apply(scope.charsRemaining);
}
element.keyup(scope.onEdit)
.keydown(scope.onEdit)
.focus(scope.onEdit)
.live('input paste', scope.onEdit);
element.on('ngChange', scope.onEdit);
var counterElement = $compile(angular.element('<span>Characters remaining: {{charsRemaining}}</span>'))(scope);
element.parent().append(counterElement);
}
}
}]);