Simple Angular Binding demo with directive
Externalize the time into a separate directive component.
by vishalvasani
HTML
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.angularjs.org/1.0.6/angular.min.js"></script>
<div ng-app='demo'>
<h3>Greeting</h3>
<p ng-controller='MyCtrl'>Hi, it's {{name}}.
The current time is <input-auto-expand ng-model="content"/>.</p>
</div>
CSS
.autoexpand-textarea-container {
position: relative;
width: 50%;
}
.autoexpand-textarea, .autoexpand-textarea-size {
min-height: 25px;
font-family: sans-serif;
font-size: 14px;
box-sizing: border-box;
padding: 4px;
border: 1px solid;
overflow: hidden;
width: 100%;
}
.autoexpand-textarea {
height: 100%;
position: absolute;
resize:none;
white-space: normal;
}
.autoexpand-textarea-size {
visibility: hidden;
white-space: pre-wrap;
word-wrap: break-word;
overflow-wrap: break-word;
}
JavaScript
var demo = angular.module('demo', []);
demo.directive('inputAutoExpand', function($parse) {
return {
restrict: 'E',
replace: false,
transclude: false,
require: 'ngModel',
template: '<div class="autoexpand-textarea-container"><textarea class="autoexpand-textarea"></textarea><div class="autoexpand-textarea-size"></div></div>',
link: function (scope, element, attrs, ngModelCtrl) {
//var currentDate = new Date();
//element.text(currentDate.toTimeString());
var textContainer, textareaSize, input;
ngModelCtrl.$render = _render;
textContainer = jQuery('.autoexpand-textarea-container');//document.querySelector('.textarea-container');
textareaSize = textContainer.find('.autoexpand-textarea-size');
input = textContainer.find('.autoexpand-textarea');
autoSize();
//input.addEventListener('input', autoSize);
input.on("input",function() {
autoSize();
})
function autoSize() {
textareaSize.html(input.val() + '\n');
};
function _render() {
console.log(ngModelCtrl.$viewValue);
textareaSize.html(ngModelCtrl.$viewValue);
input.val(ngModelCtrl.$viewValue)
}
}
}});
function MyCtrl ($scope) {
$scope.name = 'Ken';
$scope.myTime = new Date(); // now
$scope.content ="Hello world \n how r u"
};