Reputation: 1210
Using an Angular directive, I'm trying to create a vertically expandable textarea that has the same number of rows as the number of '\n' characters in the text.
(Note, I'm aware that this won't work for wrapping lines - I'll deal with this separately).
app.directive('textExpand', function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs, ngModel) {
RecalculateLines();
function RecalculateLines() {
scope.textEntry = "line1\nline2\n\nline3";
angular.element(elem).attr("rows", (scope.textEntry).split("\n").length);
}
elem.on('keydown', function(event) {
RecalculateLines();
});
}
};
});
The idea is that I have a function to constantly recount the number of line breaks and dynamically update the number of rows using angular's jqLite to set the attribute. I call that function once in the beginning (to display any pre-existing values) and then once on every keystroke.
(scope.textEntry).split("\n").length
gets correctly counted when loading the hardcoded value and updated when typing into the box. However, setting it using .attr() only seems to work on the initial call and not on keystrokes.
What's weirder is that .attr()
seems to work fine if passing it another number. See commented out code in the plunk where the box expands and shrinks fine based on a counter every keystroke.
What am I missing?
Upvotes: 0
Views: 123
Reputation: 19748
You were resetting the scope variable in the string that was checking it, moving this out of the function and adding ng-trim="false"
fixes the problem.
http://plnkr.co/edit/W0g1PupXYTUgiNLK1D8M?p=preview
function RecalculateLines() {
angular.element(elem).attr("rows", (scope.textEntry).split(/\r?\n/g).length);
// angular.element(elem).attr("rows", rowCount);
}
Upvotes: 1