gpt4 book ai didi

javascript - 更新嵌套 $scope 数组时,Angular.js View 不会更新

转载 作者:可可西里 更新时间:2023-11-01 02:04:24 24 4
gpt4 key购买 nike

我试图在添加评论时让 angular.js View 自行更新。我的代码如下:

<div class="comment clearfix" data-ng-repeat="comment in currentItem.comments" data-ng-class="{bubble: $first}" data-ng-instant>
<div>
<p>
<span class="username">{{comment.user}}</span> {{comment.message}}
</p>
<p class="time">
10 minutes ago
</p>
</div>
</div>
<div class="comment reply">
<div class="row-fluid">
<div class="span1">
<img src="assets/img/samples/user2.jpg" alt="user2" />
</div>
<div class="span11">
<textarea class="input-block-level addComment" type="text" placeholder="Reply…"></textarea>
</div>
</div>
</div>

范围在输入时更新:

$('.addComment').keypress(function(e) {
if(e.which == 10 || e.which == 13) {
$scope.currentItem.comments.push({
"user": "user3",
"message": $(this).val()
});
console.debug("currentItem", $scope.currentItem);
}
});

调试 $scope.currentItem 显示注释已添加到其中,但是 View 不显示新注释。我怀疑 $scope 仅在其第一级被监视,这就是 View 不更新的原因。是这样吗?如果是这样,我该如何解决?

解决方案:正如 Ajay 在他下面的回答中所建议的那样,我将数组 push 包装到 apply 函数中,如下所示:

var el=$(this);
$scope.$apply(function () {
$scope.currentChallenge.comments.push({
"user": $scope.currentUser,
"message": el.val()
});
});

最佳答案

修改代码以包裹在范围内。$apply 因为您正在修改必须使用的 Angular 范围之外的属性 scope.$apply()查看值

关于javascript - 更新嵌套 $scope 数组时,Angular.js View 不会更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16039076/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com