Implementing the Photo Controller

Next, you need to implement a controller to support the photo portion of the page. Listing 27.16 shows the photoController code. Notice that commentSrv is injected into the controller, along with the $http service.

The controller initializes $scope.photos and $scope.photo, using an $http GET request to the /photos route. The $scope.loadComments() function uses the commentSrv.getComment() function to retrieve the comments for the current photo by passing $scope.photo.commentId. The callback function simply sets the $commentThread value that is used in the view.

The $scope.addReply() method is called when the user clicks Send for a comment reply in the template. Notice that it first generates a newComment object with the subject and body passed in from the view and then uses commentSrv.addComment() to send the update to the server.

The $setPhoto() function accepts the photoID from the user interface and then makes an $http GET request to /photo to retrieve the photo object. $scope.photo is updated with the data, and $scope.loadComments() is called to load the comments for the new photo.

Listing 27.16 comment_app.js-photoController: Implementing an AngularJS controller that supports the photo and photo comments portions of the view


25 app.controller('photoController', ['$scope', '$http', 'commentSrv',
26                               function($scope, $http, commentSrv) {
27     $http.get('/photos')
28      .success(function(data, status, headers, config) {
29         $scope.photos = data;
30         $scope.photo = $scope.photos[0];
31         $scope.loadComments();
32       })
33       .error(function(data, status, headers, config) {
34         $scope.photos = [];
35       });
36     $scope.loadComments = function(){
37       commentSrv.getComment($scope.photo.commentId,
38                             function(err, comment){
39         if(err){
40           $srope.commentThread = {};
41         } else {
42           $scope.commentThread = comment;
43         }
44       });
45     };
46     $scope.addReply = function(parentCommentId, subject, body){
47       var newComment = {subject:subject, body:body};
48       commentSrv.addComment($scope.commentThread._id,
49                             parentCommentId,
50                             newComment, function(err, comment){
51           $scope.loadComments();
52         });
53     };
54     $scope.setPhoto = function(photoId){
55       $http.get('/photo', {params: {photoId: photoId}})
56         .success(function(data, status, headers, config) {
57             $scope.photo = data;
58             $scope.loadComments();
59           })
60         .error(function(data, status, headers, config) {
61             $scope.photo = {};
62           });
63     };
64   }]);


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.53.168