AngularJS - Simple Directive Use

by Tushar Jadhav

HTML

<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/css/bootstrap.css">
<script src="http://code.angularjs.org/1.0.0/angular-1.0.0.js"></script>
<div ng-app="myApp">
    <div>
        <resize-textarea></resize-textarea>
    </div>
</div>

JavaScript

angular.module('myDirectives', []).directive('resizeTextarea', function () {
    return {
        restrict: 'E',
        transclude: true,
        replace: true,
        template: "<textarea placeholder='please fill in...'></textarea>",
        link: function (scope, element, attrs) {
            var HEIGHT = 25;
            var el = angular.element(element[0])
            el.css('lineHeight', HEIGHT + "px");
            el.css('height', HEIGHT + "px");

            var resize = function (e) {
                el.css({
                    'height': 'auto',
                        'height': this.scrollHeight + 'px'
                });

            };
            el.on('input', resize);
        }
    };
});
angular.module('myApp', ['myDirectives']);