As a newcomer to Angular, I have a seemingly simple question regarding setting up a comments system for articles. I've implemented two angular controllers - one for loading comments upon page load and another for submitting new comments to the server. While these functions work well individually, I'm facing issues in updating the displayed comments with the newly submitted comment within the success()
method. Despite trying various methods, my current code fails to achieve this. Can someone please assist me?
I suspect the issue lies in handling different $scope
variables, however, the documentation available hasn't cleared up my confusion.
article.js
// initialize app
var articleApp = angular.module('articleApp', ['btford.markdown', 'ngSanitize']);
// define controllers
articleApp.controller('DisplayCommentsCtrl', function ($scope, $http) {
$scope.loadComments = function () {
$http.get(Routing.generate('article_comments', { id: window.articleId })).success(function (data) {
$scope.comments = data.comments;
});
};
$scope.loadComments();
});
articleApp.controller('SubmitCommentCtrl', function ($scope, $http, $route) {
$scope.loadComments = function () {
$http.get(Routing.generate('article_comments', { id: window.articleId })).success(function (data) {
$scope.comments = data.comments;
});
};
$scope.loadComments();
$scope.formData = {
'comment':{
'save' : 'Save',
'comment' : '',
'_token' : $('#comment__token').val()
}
};
$scope.processForm = function ($route) {
$http({
method : 'POST',
url : Routing.generate('article_new_comment', { id: window.articleId }),
data : $.param($scope.formData),
headers : {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.success(function (data, $route) {
$route.reload();
});
};
});
article.html.twig
<div class="col-md-12">
<div class="commentFormContainer" ng-controller="SubmitCommentCtrl">
{% verbatim %}
<p>{{ formData.comment.comment }} / {{ formData.comment._token }}</p>
{% endverbatim %}
<!--{{ form_start(commentForm, { 'attr': { 'id': 'commentForm', 'ng-submit':'processForm()' }}) }} -->
<form name="comment" id="commentForm" ng-submit="processForm()">
{{ form_errors(commentForm) }}
{{ form_row(commentForm.comment, { 'attr': { 'ng-model': 'formData.comment.comment' } }) }}
{{ form_widget(commentForm._token) }}
{{ form_end(commentForm) }}
</div>
{% verbatim %}
<div class="articleCommentContainer" ng-controller="DisplayCommentsCtrl">
<div ng-repeat="comment in comments | orderBy: '-time'">
<div class="articleCommentComment" ng-bind-html="comment.commentHTML">
</div>
<div class="articleCommentDetails">
<p>[{{ comment.creator }} @ {{ comment.time|date:'EEE d MMM, h.mm a' }}]</p>
</div>
</div>
</div>
{% endverbatim %}
</div>