I have created a directive with a controller that is responsible for building a form to post comments to an API through CommentsService
Here is a snippet of how my directive looks:
app.directive('appComments', function( CommentService ) {
return {
restrict: 'E',
scope: {
event: '='
},
controller: function( $rootScope, $scope, $element ) {
$scope.comments = [];
$scope.comment_text = '';
// load comments if event ID has changed
$scope.$watch( 'event', function() {
if( typeof $scope.event != 'undefined' ) {
CommentService.get( $scope.event ).then(
function( comments ) {
$scope.comments = comments;
}
);
}
});
// post comment to service
$scope.postComment = function() {
if( $scope.comment_text != '' ) {
CommentService.post(
$scope.event,
$scope.comment_text,
function() {
// code to reload comments
}
);
}
};
},
templateUrl: '/partials/comments.html'
};
});
This is the content of my comments.html file used by the directive
<div class="event-comments">
<p ng-if="!comments.length">
<span>This event has no comments.</span>
</p>
<div
class="event-comment"
ng-repeat="comment in comments"
>
<div class="comment-text">{{comment.text}}</div>
</div>
</div>
<div class="insert-comment-container" ng-if="!loading">
<form ng-submit="postComment()">
<textarea
ng-model="comment_text"
></textarea>
<div
ng-tap="postComment()"
>Post</div>
</div>
</div>
This is how I've included it in my main view:
<app-comments event="event.id"></app-comments>
The comments are loading correctly and the event ID is being passed successfully. However, when I try to post a comment, the `comment_text` field appears blank.
I suspect there may be some confusion with scopes or bindings within my directive implementation as I'm still learning about directives.
** update **
I just realized that if I set
$scope.comment_text = 'Initial text'
inside the directive, it displays "Initial text" in the textarea upon rendering the template. When I change the text in the textarea and click the post button, the value of `$scope.comment_text` remains "Initial text". It seems like there is a one-way binding issue at play.