Reputation: 4422
I have a form for submitting a comment with two-way binding to an AngularJS 1.4 controller. When a comment is sent, I would like to clear the comment-textarea and resize it to one row using autosize()
from the library http://www.jacklmoore.com/autosize/ .. Autosize is used for resizing the textarea
if a user types a long comment.
However, it seems the autosize
happens before the comment input is cleared out. So this means the textarea will remain the size of the entered text.
This code works, but I find it ugly to just wait 50ms. What should I do to ensure the textarea
two-way binding has been updated before calling $scope.updateTextareaSize();
?
My code is
commentService.storeComment($scope.text)
.success(function(data, status, headers, config) {
$scope.text = ''; // The comment which is two-way bound.
setTimeout(function() { $scope.$evalAsync(
$scope.updateTextareaSize() ); // Call autosize()
}, 50); // Update textarea size after the angular bindings have updated. Assuming this is done in 50ms.
})
Upvotes: 1
Views: 61
Reputation: 16435
You can instead use the $timeout service with a timeout of 0.
$timeout(function() {
$scope.updateTextareaSize() // Call autosize()
}, 0);
When you do this it makes your $scope.updateTextareaSize()
function run after all of Angular's internal plumbing in the $digest
such as updating the two way binding.
Upvotes: 4