I'm new to Angular, so apologies in advance for what I predict is a simple question. I'm trying to create a comments system for articles. I have two angular controllers, one to load the comments when the page is loaded, and another to submit a new comment to the server. These work fine, but in the success()
method I'd like to update the displayed comments to show the new comment. However, my code at present doesn't work and no method I've tried seems to fix it. Could I get some help please?!
I know this is probably to do with different $scope
variables, but none of the documentation I've read seems to make this clear.
article.js
// create app
var articleApp = angular.module('articleApp', ['btford.markdown', 'ngSanitize']);
// create controller
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>