【发布时间】:2018-11-05 11:57:02
【问题描述】:
我是 AngularJs 的新手,我遇到了 ng-repeat 的问题。基本上,我想使用 ajax 从我的数据库中获取与文章相关的 cmets,然后使用 ng-repeat 显示它们。然后我有一个数组,我在其中推送我的 cmets。我的问题是,当我在数组中手动创建注释时,效果很好,但是如果我从 ajax 函数的回调中自动推送此注释,则数组会更新,但我的视图不会更新。
在 html 中查看:
var articleApp = angular.module('articleApp', []);
articleApp.controller('CommentsController', function CommentsController($scope) {
$scope.comments = [];
// This push works well, my view is updated
$scope.comments.push({
content: "Hello world !",
date: "2 minutes ago",
id: 29,
author: {
pseudo: "Sean"
}
});
// When I push with this function, my array is updated, but not the view
$scope.addComment = function(comment) {
$scope.comments.push({
content: comment.comment,
id: comment.id,
date: comment.date_post,
author: {
id: comment.author.id,
pseudo: comment.author.pseudo
}
});
};
var articleID = document.getElementById('articleID').textContent;
// getComments is defined elsewhere, and returns the 20 first comments
getComments(20, articleID, 0, function(comments) {
for(var i = 0; i < comments.length; i++) {
$scope.addComment(comments[i]);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<section id="commentsSection" class="bottom_apps" ng-controller="CommentsController as comments">
<article id = "{{comment.id}}" class="comment_container" ng-repeat="comment in comments">
<div class="comment_header">
<span class="comment_author">{{comment.author.pseudo}}</span>
<span class="comment_date">{{comment.date}}</span>
</div>
<div class="comment_content">
{{comment.content}}
</div>
</article>
</section>
我反复检查了我所有的代码,但我看不出哪里出错了。
【问题讨论】:
-
将
ng-controller="CommentsController as comments"更改为ng-controller="CommentsController"。始终进行四次检查 -
它似乎改变了什么:/
-
getComments未定义 -
好吧,您调用
$scope.addComment的代码没有任何意义。id没有在任何地方定义,在您的 HTML 中它们是动态的;getComments未定义;您的任何代码都没有显示您如何使用 AJAX 调用任何内容。否则,这里是working example -
好吧,我没有粘贴我所有的代码,articleID 和 getComments() 都已定义并且可以正常工作。我知道它们可以工作,因为在 addComment() 之后使用 console.log($scope.comment),我看到我的数组确实包含我所有的 cmets。
标签: javascript angularjs angularjs-ng-repeat frontend