确保AngularJS双向绑定更新 [英] Making sure AngularJS two-way binding is updated

查看:141
本文介绍了确保AngularJS双向绑定更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我提交双向绑定到AngularJS 1.4控制器评论的形式。当发送评论,我想清楚了注释的文本区域,并使用自动调整()从库中的 http://www.jacklmoore.com/autosize/ ..自动调整用于调整大小的textarea 如果用户键入一个长注释。

然而,似乎在自动调整发生在注释输入被清除之前。因此,这意味着textarea的仍将是输入的文本的大小。

这code的作品,但我觉得它难看,只是等待50毫秒。我应该怎么做,以确保的textarea 双向绑定调用之前已更新 $ scope.updateTextareaSize();

我的code是

  commentService.storeComment($ scope.text)
    .success(功能(数据,状态,头,配置){
        $ scope.text =''; //注释这势必双向的。        的setTimeout(函数(){$范围。$ evalAsync(
            $ scope.updateTextareaSize()); //调用自动调整()
        },50); //角绑定后更新textarea的大小已经更新。假设这是50毫秒完成。
})


解决方案

您可以改为使用的 $超时服务为0的超时。

  $超时(函数(){
    $ scope.updateTextareaSize()//调用自动调整()
},0);

当你做到这一点使你的 $ scope.updateTextareaSize()函数后的 $消化如更新双向绑定。

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.
})

解决方案

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.

这篇关于确保AngularJS双向绑定更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆