当嵌套$范围数组更新Angular.js视图不更新 [英] Angular.js view doesn't update when nested $scope array is updated
问题描述
我想添加注释时,使自己的angular.js视图更新。我的code是如下:
< DIV CLASS =评论clearfix数据-NG-重复=,在currentItem.comments评论数据-NG-CLASS ={泡沫:$第一}数据 - NG-即时>
< DIV>
&所述p为H.;
<跨度类=用户名> {{comment.user}}< / SPAN> {{comment.message}}
&所述; / P>
< p =类时间>
11分钟前
&所述; / P>
< / DIV>
< / DIV>
< DIV CLASS =评论回复>
< DIV CLASS =排液>
< DIV CLASS =span1>
< IMG SRC =资产/ IMG /样本/ user2.jpgALT =用户2/>
< / DIV>
< DIV CLASS =span11>
< TextArea类=输入块级addComment类型=文本占位符=回复......>< / textarea的>
< / DIV>
< / DIV>
< / DIV>
范围更新输入:
$('。addComment')。重点preSS(函数(五){
如果(e.which == || 10 == e.which 13){
$ scope.currentItem.comments.push({
用户:用户3
消息:$(本).VAL()
});
console.debug(CURRENTITEM,$ scope.currentItem);
}
});
调试$ scope.currentItem表明,评论已被添加到它,但是视图不显示新的注释。我怀疑$范围仅仅被监视其第一级,这就是为什么视图不会更新。是这样吗?如果是的话我该如何解决?
解决方案:
由于阿贾伊在他的回答以下建议我包数组大举进军应用函数是这样的:
VAR EL = $(本);
$范围。$应用(函数(){
$ scope.currentChallenge.comments.push({
用户:$ scope.currentUser,
消息:el.val()
});
});
修改code内部范围来包装。$适用,因为要修改的角度范围之外的属性,你必须使用的 $范围适用于()观看值
。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
这篇关于当嵌套$范围数组更新Angular.js视图不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!