AngularJS1 + Django REST Frameworkに再挑戦 その12 Comment Reply Directive
概要
AngularJS1 + Django REST Frameworkに再挑戦 その12 Comment Reply Directive
参考動画
Django + AngularJS | Coding For Entrepreneurs
Reply to Comments part1
- js/app/comment/comment.directive.js を作成する。
'use strict'; angular.module('core.comment'). // Commentも読み込む directive('commentThread', function(Comment){ return { restrict: "E", scope: { }, template: "<ul><li>Reply</li></ul>", link: function(scope, element, attr){ } } })
home.htmlに、
<script src='{% static "js/app/core/comment/comment.directive.js" %}' ></script>
に読み込ませる。ここで1点ポイントは、
comment.directive.js
の後に読み込ませる。なぜなら、comment.directive.js
内の、Commentモジュールを継承したいため。blog-detail.htmlに、
<comment-thread></commentThread>
を追記することで、commentThreadを利用できる。最終的に以下のようにcomment.directive.jsを修正する。
angular.module('core.comment'). directive('commentReplyThread', function(Comment){ return { restrict: "E", scope: { comment: '=comment', }, template: "<ul ng-show='replies'><li ng-repeat='reply in replies'>{{ reply.content }}</li></ul>" + "<div class='text-center' ng-show='!replies'><img style='margin: 0 auto;' ng-src='/static/img/ring.gif' class='img-responsive'/><div>", // ng-src='/static/img/ring.gif'ここで、アニメーションがちょっと使える! // loading.ioという所のgifアニメを使うといいぽいな。 link: function(scope, element, attr){ if (scope.comment){ var commentId = scope.comment.id if (commentId){ Comment.get({id: commentId}, function(data){ scope.replies = data.replies }) } } } } })
Reply to Comments part2
- blog-detailの一部を、comment.directive.jsのtemplateに埋め込む
'use strict'; angular.module('core.comment'). directive('commentReplyThread', function(Comment){ return { restrict: "E", scope: { comment: '=comment', }, template: "<ul ng-show='replies'><li ng-repeat='reply in replies'>{{ reply.content }}</li></ul>" + "<div class='text-center' ng-show='!replies'><img style='margin: 0 auto;' ng-src='/static/img/ring.gif' class='img-responsive'/>" + "</div>" + "<p style='color:red;' ng-if='reply.content'>Preview: {{ reply.content }}</p>" + "<form ng-submit='addCommentReply(reply, comment)'>" + "<textarea class='form-control' ng-model='reply.content'></textarea>" + "<input class='btn btn-default btn-sm' type='submit' value='Reply'/>" + "</form>", // ng-src='/static/img/ring.gif'ここで、アニメーションがちょっと使える! // loading.ioという所のgifアニメを使うといいぽいな。 link: function(scope, element, attr){ if (scope.comment){ var commentId = scope.comment.id if (commentId){ Comment.get({id: commentId}, function(data){ scope.replies = data.replies }) } } } } })
- 一旦indexpageなどに直接コードをかく->angularのtemplateに一部埋め込む->angularのtemplateのhtmlを作成する という流れが一番わかりやすくてミスが少ないかもしれない。