0

I'm creating a MEAN stack blog app and what I'm trying to accomplish is getting a "blog" from a list of blogs(div with ng-repeat) which I have saved to my Mongo database using a Mongoose schema to render in a seperate HTML view.

Specifically, I want to be able to click on the <button class="readPost" ng-click="readPost(post._id)">Read Blog</button> in main.html and have that data to be rendered through AngularJS' data-binding in readblog.html.

What I have tried:

1.) I have tried putting a $location.path('/readblog' + id); in the readPost function, but I'm assuming that doesn't work if that path is not specifically declared in my app.js file.

2.) Putting a res.redirect('/readblog'); and a res.redirect('/readblog' + id); in the API call in server.js.

...and now I'm currently looking to see if there are any examples of this problem or alternative methods for achieving this functionality I'm trying to get.

I'm fairly new to coding in general, so I will be happy to clarify on anything that doesn't necessarily make sense here.

Here's what my code looks like:

server.js

//Dependencies.

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');
var mongoose = require('mongoose');
var http = require('http');
var path = require('path');
var fs = require('fs');

var port = 9001;
var mongoUri = 'mongodb://localhost:27017/blog-app';

var app = express();

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());

var Schema = mongoose.Schema;

var blogSchema = new Schema({
    title : {type: String, min: 8, max: 50, required: true},
    body : {type: String, required: true},
    author : {type: String, min: 3, max: 40, required: true},
    pubdate : {type: Date, default: Date.now}
});

var Blog = mongoose.model('Blog', blogSchema);

app.get('/api/blogs/:blog_id', function(req, res) { //Get Blog by ID.
    Blog.find({
        _id: req.params.blog_id
    }, function(err, blog) {
        if (err)
            res.send(err);
    });
});


mongoose.connect(mongoUri);
mongoose.connection.once('open', function() {
  console.log("We are now connected to MongoDB at: ", mongoUri);
});

app.listen(port, function() {
  console.log('Listening on port: ', port);
});

mainCtrl.js

var app = angular.module("blog-app");

app.controller('MainController', ['$scope', '$http', '$location', function($scope, $http, $location) { 

  $scope.apptitle = "AngularJS Blog";

  $scope.formData = {};

  $http.get('/api/blogs').success(function(data){
      $scope.blog = data;
      console.log(data);
    }).error(function(data) {
      console.log('Error: ' + data);
    });



 $scope.readPost = function(id) {
    $http.get('/api/blogs/' + id)
      .success(function(data) {
        $scope.readblog = data;
        console.log('This is the blog you selected: ', data);
      });
  };

}]);

app.js

var app = angular.module('blog-app', ['ngRoute']);

app.config(function($routeProvider) {

    $routeProvider

    .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainController'
    })

    .when('/newblog', {
        templateUrl: 'views/newblog.html',
        controller: 'MainController'
    })

    .when('/readblog', {
        templateUrl: 'views/readblog.html',
        controller: 'MainController'
    })

    .otherwise({
      redirectTo: '/'
    });

}) //End Config.

main.html

<div>
    <div class="wrapper"> 
        <div class="container" ng-repeat="post in blog">  
            <p><i class="fa fa-book"></i>&nbsp;{{ post.title }}</p>
            <p>by {{ post.author}}</p> 
            <p>{{ post.pubdate | date }}</p>
            <br>
            <div>
                <p>{{ post.body }}</p>
            </div>
            <br><br>
            <div style="position: absolute; bottom: 10px; right: 10px;">
                <button class="deletePost" ng-click="deletePost(post._id)">Delete Blog</button>
                <button class="readPost" ng-click="readPost(post._id)">Read Blog</button>
            </div>
        </div>
    </div>
</div>

readblog.html

<div style="padding-top: 150px">
<h2>Title: {{ readblog.title }}</h2>
<h2>Author: {{ readblog.author }}</h2>
<h2>Date: {{ readblog.pubdate }}</h2>
<h2>Body: {{ readblog.body }}</h2>
</div>

2 Answers2

0

What you can do is drop your ngclick and use nghref to navigate to the blog post with selected id, then async load it and and assign it to your blog post scope.

If you have to do it programmatically, use $location and define path for the blog to accept id's.

 .when('/readblog/:blogId',...

Similar question

Community
  • 1
  • 1
epliXs
  • 1
  • 1
0

First of all, we need to separate two things; client and server. Your issue here is about the client side. I suggest you reading through https://github.com/angular-ui/ui-router documentation for your purpose; that is to pass data from one state to another. In your case it is the blogid of the selected blog. Then in your second state, you can retrieve your blogid by $Stateparams and by making a get request to your server to

/api/blogs/:blog_id

Something like

$stateProvider .state('blog', { url: "/blogs", templateUrl: "views/blog.html" }) .state('readblog', { url: "/blogs/:blogid", templateUrl: "views/readblog.html", params: { 'id':'123456' })

would do the work.

Serhan Oztekin
  • 475
  • 7
  • 20
  • I switched over to ui.router, because it's apparently more robust and I saw that the syntax in your answer indicated that you would use it over ngRoute? Anyways... with the params key, can I just put "_id" there as the value to target the blog I select by click? – Princeton Collins May 09 '16 at 18:48
  • @PrincetonCollins I'd prefer ui router yes. Putting _id as the indicator of the selected object (in this case its the selected target blog entry) is the best solution. So that means Yes, you would want to use "id" – Serhan Oztekin May 09 '16 at 18:52
  • I tried passing in 'id as the value for key 'id'. But it seems to be returning my whole database. Maybe you could take a look at my project in github and tell me what the problem is, if you have time. Here's the github repo: https://github.com/princetoncollins/blog-app – Princeton Collins May 09 '16 at 19:40
  • Still having this issue if anyone has time to look at this code. – Princeton Collins May 11 '16 at 21:49
  • Sorry im quite busy these days, i guess i wont be able to look at the whole code @PrincetonCollins – Serhan Oztekin May 12 '16 at 08:02