Reputation: 127
I'm trying to change the height of a textarea using AngularJS within a directive. I add an attribute auto-resize
to my textarea
and have the directive defined as:
app.directive('autoResize',function(){
return {
restrict: 'A',
//scope: {},
replace: false,
link: function(scope, element, attrs) {
element.css({
'overflow': 'hidden',
'color': 'red',
'height': '50px'
});
}
}
}
The color and overflow styles are implemented onto the textarea, however the height of the text-area does not go to 50px.
Any help is appreciated.
Upvotes: 1
Views: 1214
Reputation: 3044
This directive might do what you're looking for :)
Here is a codepen showing it working: https://codepen.io/benshope/pen/xOPvpm
app.directive('expandingTextarea', function () {
return {
restrict: 'A',
controller: function ($scope, $element, $attrs, $timeout) {
$element.css('min-height', '0');
$element.css('resize', 'none');
$element.css('overflow-y', 'hidden');
setHeight(0);
$timeout(setHeightToScrollHeight);
function setHeight(height) {
$element.css('height', height + 'px');
$element.css('max-height', height + 'px');
}
function setHeightToScrollHeight() {
setHeight(0);
var scrollHeight = angular.element($element)[0]
.scrollHeight;
if (scrollHeight !== undefined) {
setHeight(scrollHeight);
}
}
$scope.$watch(function () {
return angular.element($element)[0].value;
}, setHeightToScrollHeight);
}
};
});
Upvotes: 1
Reputation: 816
You must to use 'style' for manipulation of css attributes at the DOM level instead 'css()'. You can use the '.css()' method when you are using jQuery. Try this in your directive.
element.style.height = '50px';
element.style.overflow = 'hidden';
element.style.color = 'red';
See reference here
Upvotes: 0
Reputation: 5786
you should set the rows attribute on a textarea rather than changing the height through css.
app.directive('autoResize',function(){
return {
restrict: 'A',
//scope: {},
replace: false,
link: function(scope, element, attrs) {
element.css({
'overflow': 'hidden',
'color': 'red'
});
element.attr("rows", 5);
}
}
}
http://www.w3schools.com/tags/att_textarea_rows.asp
Upvotes: 0