Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
248 views
in Technique[技术] by (71.8m points)

javascript - Angular.js view doesn't update when nested $scope array is updated

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()
     });
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...