"Step-by-step guide on showcasing a specific blog post using its unique identifier in an Angular/Express/MongoDB application

I'm struggling to figure out how to retrieve a single blog post by its ID, especially since I am new to this.

Currently, my main blog application has an ng-repeat functionality that fetches all posts. What I really want is the ability to click on a post's name and have only that specific post displayed, without any distractions — eventually, I aim to incorporate options for editing and deleting based on the post's ID.

I am aware of the existence of filters, but I am uncertain about enabling a filter through clicking or ensuring that it accurately filters by the _id when clicked.

The code snippet in 'post.html' appears as follows -

<div ng-controller="PostController" class="panel panel-default">
    <div class="panel-heading">
        <h3 class="panel-title">
            <strong>
                <a href ng-click="selectTab('viewPost')">{{post.title}}</a>
            </strong> created on {{post.time | date: 'MM/dd/yy @ h:mma'}}
        </h3>
    </div>
    <div class="panel-body">
        {{post.body}} <br>
        {{post._id}}
    </div>
</div>

For now, the ng-click directive is set up to display this-

        <div ng-show="isSelected('viewPost')">
          <view-post></view-post>
        </div>

This corresponds to a custom directive linked with this file --

<div class="panel panel-default">
<div class="panel-heading">
    <h3 class="panel-title">
        <strong>
            <a href>{{postById.title}}</a>
        </strong> created on {{postById.time | date: 'MM/dd/yy @ h:mma'}}
    </h3>
</div>
<div class="panel-body">
    {{postById.body}}


</div>
</div>

However, when this template is displayed, the expressions seem to be missing entirely.

There is a getPost function in my controller 'PostController,' but I am unsure how to utilize it.

    $scope.getPost = function () {

        $http({method: 'GET', url: '/api/blog/:post_id', data: $scope.postById})
        .then(function(response){
             //your code in case the post succeeds
            console.log(response);
            })
        .catch(function(err){
            //your code in case your post fails
            console.log(err);
            });

        }

The API functions correctly using Postman, allowing me to retrieve/update/delete posts on that route. Currently, I do not have any specific routes set up in the address bar — everything revolves around custom directives displaying the desired templates upon clicking.

I suspect it might be a problem related to the scope of my controllers.

A segment of my HTML could provide more clarity--

<body ng-controller="PanelController">

<div class="site-wrapper">
  <div class="site-wrapper-inner">
    <div class="cover-container">
      <div class="masthead clearfix">
        <div class="inner">
          <nav-bar></nav-bar>
      </div>

      <div ng-controller="PostController">
        <div ng-show="isSelected('blog')">
          <div ng-repeat="post in posts | orderBy: 'time':true">
            <blog-post></blog-post>
          </div>
        </div>

        <div ng-show="isSelected('about')">
          <about-page></about-page>
        </div>

        <div ng-show="isSelected('contact')">
          <contact></contact>
        </div>

        <div ng-show="isSelected('createPost')">
          <create-post></create-post>
        </div>

        <div ng-show="isSelected('viewPost')">
          <view-post></view-post>
        </div>

      </div>
    </div>

Hoping this information resonates with someone who can assist. Any guidance would be highly appreciated.

UPDATE: To offer additional context, here is the API endpoint for retrieving posts by ID -

router.route('/blog/:post_id')

.get(function(req, res) {
    Post.findById(req.params.post_id, function(err, post) {
        if (err) {
            res.send(err);
        } else {
            res.json(post);
        }
    });
})

.put(function(req, res) {

    Post.findById(req.params.post_id, function(err, post) {

        if (err) {
            res.send(err);
        } else {
            post.title = req.body.title;
            post.body = req.body.body;
        }

        post.save(function(err) {
            if (err) {
                res.send(err);
            } else {
                res.json({ message: 'Post updated!' });
            }
        });

    });
})

.delete(function(req, res) {
    Post.remove({
        _id: req.params.post_id
    }, function(err, post) {
        if (err) {
            res.send(err);
        } else {
            res.json({ message: 'Successfully deleted' });
        }
    });
});

Answer №1

To store the received data, make sure to assign it to $scope.post. Here's an example of how you can do it:

$http(...).then(function(response) {
    $scope.post = response.data;
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the art of path zooming in d3.js

Trying to resolve this issue, I adjusted the geoJsonURL to handle a more intricate shape. Despite the new shape allowing the zoom method to function correctly, the shape itself appears completely distorted. Based on the Coordinate system: WGS 84 (EPSG:4326 ...

ngAnimateSwap - animations do not function as intended when boolean expressions are utilized

I adapted the original ngAnimateSwap demonstration from the AngularJS documentation to utilize a boolean expression for triggering the slide animation. Initially, I anticipated the banner to switch back and forth between 'true' and 'false&a ...

What is the best way to send ServerSideProps to a different page in Next.js using TypeScript?

import type { NextPage } from 'next' import Head from 'next/head' import Feed from './components/Feed'; import News from './components/News'; import Link from 'next/link'; import axios from 'axios&apo ...

What is preventing Javascript from executing a function when there is an error in another function?

Can you explain why a JavaScript function fails to run if there is an error in another function? Recently, I encountered an issue on my HTML page where the alert from the popup1() function would not load. It turns out the problem stemmed from an error in ...

After two HTML injections, Javascript ceases to function properly

I am in the process of developing a chat feature for my website. The layout includes a conversation section on the left and a list of users on the right. When a user's div is clicked, their ID is transmitted to the Django back end. Subsequently, full ...

What is the best way to generate a div with a dynamically changing variable as its ID?

Creating a quiz where the user can choose how many questions to answer. A function is used to generate individual question divs based on the user's input. Each question displays a Chinese character, and the user must select the correct translation. ...

Uncovering the Secret to AngularJS Form Validation: Retrieving Controller Values

This is my unique HTML code: <form name="userForm" ng-submit="submitForm()" novalidate> <!-- NAME --> <div class="form-group" ng-class="{ 'has-error' : userForm.name.$invalid &a ...

Searching for related values in a nested array of objects using JavaScript: A guide

My goal for this project is to thoroughly examine the path along with all nested elements within the Items and assign them to the details variable. However, due to the limitations of the function inside the useEffect, I am unable to check nested items eff ...

Activate the Alert (https://material-ui.com/components/alert/#alert) starting from the React component at the bottom of the hierarchy

When it comes to alerts, a normal alert is typically used like alert("message to be displayed");. However, I prefer using material UI Alerts which return a JSX component. For example: <Alert severity="success">This is a success alert — check it out ...

Tips for including a JWT token as a query parameter in NEXT js?

const UserJwt = (props) => { const { jwt } = props; const [jwtToken, setJwtToken] = useState(null); useEffect(() => { if (jwt) { setAuthToken(jwt); setJwtToken(jwt); } }, [jwt]); return <MobilePurchaseScreen {...pro ...

Condition-based React state counter starts updating

In my current project, I have developed the following React component: import React from "react"; import ReactDOM from "react-dom"; import { WidthProvider, Responsive } from "react-grid-layout"; import _ from "lodash"; const ResponsiveReactGridLayout = Wi ...

Show the current time using Moment.js

I am currently working on developing a clock component that displays the current time in real-time. Issue: The initial time is correctly displayed when the page loads (HH:mm A), but the clock does not update dynamically. clock.component.ts : import { ...

Real-time database logging triggered by Firebase user authentication

exports.setupDefaultPullups = functions.auth.user() .onCreate( async (user) => { const dbRef= functions.database.ref; let vl= await (dbRef.once('value').then( (snapshot) => { return snapsh ...

Transforming two child arrays within an object into a single array using Ramda

I am looking to transform an object into an array. The object I have is structured like this: const data = { t1: [ {"a": 1, "a1": 2}, {"b": 3, "b1": 4}, {"c": 5, "c1": 6} ], t2: [ {" ...

bespoke validation using AngularJS

Consider a scenario where there is a table comprising of 10 rows and each row contains 10 columns of checkboxes. Prior to the user submitting the form, it is necessary to implement a validation rule: at least two checkboxes must be checked in each row! & ...

What is the best way to retrieve an input value within a controller?

I am attempting to create a live search feature for an app. I have implemented an ng change function that logs the input (ng model searchLive) and triggers a reload of the http request. However, the $scope.searchlive returns undefined even though the ng ch ...

Iterating through textboxes and buttons to trigger actions in JavaScript

Having an issue with JavaScript (or jQuery) where I can successfully input text and click a button on a page using the following script: document.getElementsByName('code')[0].value='ads0mx0'; document.getElementsByName('event&a ...

Attempting to showcase the text within an <a> element on a <canvas> element while ensuring there are no noticeable visual distinctions

Imagine having this snippet of code on a webpage: elit ac <a href="http://www.ducksanddos/bh.php" id='link'>Hello world!</a> nunc Now, picture wanting to replace the <a> tag with a <canvas> element that displays the same ...

Assigning ng-view to "NAME" using RouteProvider

I'm completely new to Angular and I have a question regarding injecting a template or URL into multiple ng-views. However, my current approach involves having ng-view in my base template. My base template structure is as follows: <body> < ...

Using an asynchronous pipe filter with the ngFor loop in Angular 2 for efficient data

I have a JSON array that I need to iterate through in order to display data using an NGfor Loop. My goal is to apply filters after the data has been loaded to refine the results. The issue I am facing is that my pipe filter is returning 'cannot read p ...