Make sure AngularJS two-way binding is updated

I have a form for posting a comment with two-way binding to an AngularJS 1.4 controller. When a comment is posted, I would like to clear the comment-textarea and resize it to one line using autosize()the library http://www.jacklmoore.com/autosize/ .. Autosize is used to resize textareaif the user enters a long comment.

However, it seems that autosizehappens before the comment request is deleted. Thus, this means that textarea will remain the size of the entered text.

This code works, but I find it ugly to just wait 50ms. What to do to ensure two-way binding has textareabeen updated before the call $scope.updateTextareaSize();?

My code

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.
})
+1
source share
1 answer

Instead, you can use the $ timeout service with a timeout of 0.

$timeout(function() {
    $scope.updateTextareaSize() // Call autosize()
}, 0);

When you do this, it will run your function $scope.updateTextareaSize()after the Angular internal plumbing is built in $digest, for example, updating a two-way binding.

+4
source

Source: https://habr.com/ru/post/1622582/


All Articles