- 首页
- 前端开发
- 更新嵌套的 $scope 数组时,Angular.js 视图不会更新
更新嵌套的 $scope 数组时,Angular.js 视图不会更新
[英] Angular.js view doesn't update when nested $scope array is updated
本文介绍了更新嵌套的 $scope 数组时,Angular.js 视图不会更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我试图在添加评论时让 angular.js 视图自行更新.我的代码如下:
<div class="评论回复"><div class="row-fluid"><div class="span1"><img src="assets/img/samples/user2.jpg" alt="user2"/>
<div class="span11"><textarea class="input-block-level addComment" type="text" placeholder="回复..."></textarea>
范围在输入时更新:
$('.addComment').keypress(function(e) {if(e.which == 10 || e.which == 13) {$scope.currentItem.comments.push({"user": "user3",消息":$(this).val()});console.debug("currentItem", $scope.currentItem);}});
debugging $scope.currentItem 显示评论已添加到其中,但视图并未显示新评论.我怀疑 $scope 仅在其第一级被监视,这就是视图不更新的原因.是这样吗?如果是这样,我该如何解决?
解决方案:正如 Ajay 在他下面的回答中所建议的那样,我将数组推送包裹到应用函数中,如下所示:
var el=$(this);$scope.$apply(function () {$scope.currentChallenge.comments.push({用户":$scope.currentUser,消息":el.val()});});
解决方案
修改代码以包裹在作用域内.$apply 因为你正在修改 angular 作用域外的属性,你必须使用 scope.$apply() 观察值
I am trying to make an angular.js view update itself when adding a comment. My code is as follows:
<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>
the scope is updated on enter:
$('.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);
}
});
debugging $scope.currentItem shows that the comment has been added to it, however the view doesn't show the new comment. I suspect that the $scope is only being watched on its first level and that this is why the view doesn't update. is that the case? If so how can I fix it?
SOLUTION:
As Ajay suggested in his answer below I wrapped the array push into the apply function like this:
var el=$(this);
$scope.$apply(function () {
$scope.currentChallenge.comments.push({
"user": $scope.currentUser,
"message": el.val()
});
});
解决方案
Modify the code to wrap inside scope.$apply because you are modifying the property outside the angular scope you have to use scope.$apply() to watch the values
这篇关于更新嵌套的 $scope 数组时,Angular.js 视图不会更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!