Retrieve the unique identifier for a single post from a JSON file using AngularJS

Trying to figure out how to work with frontend and a JSON file for my data, without the usual node/express backend setup. Currently, I have a list of posts displaying but now I want to be able to fetch the unique post:id when clicking on a button.

A simple example of posts.json:

[{
  id: 1,
  title: 'Simple title1',
  content: 'Sample content...',
  permalink: 'simple-title1',
  author: 'Peter',
  datePublished: '2012-04-04'
 }, {
  id: 2,
  title: 'Simple title2',
  content: 'Sample content...',
  permalink: 'simple-title2',
  author: 'Peter',
  datePublished: '2012-05-04'
 }, {
   id: 3,
  title: 'Simple title3',
  content: 'Sample content...',
  permalink: 'simple-title3',
       author: 'Thomas',
  datePublished: '2012-06-04'
}]

Snippet from my app.js file:

var routerApp = angular.module('routerApp', ['ui.router']);

routerApp.config(function($stateProvider, $urlRouterProvider) {

$urlRouterProvider.otherwise('/home');

$stateProvider

.state('home', {
    url: '/posts',
    templateUrl: 'partial-home.html',
    controller: function($scope, $http){
    $http.get('posts.json')
    .success(function(data){
    $scope.posts = data;
    });
    }
})

          .state('viewdetails',{
    url:'/posts/:id/:permalink',
    templateUrl: 'view_details.html',
    controller: function($scope, $http){
    $http.get('source.json')
   //get a single post here???
    } }

Coding snippet from partial-home.html:

<div class="row" style="margin-left:50px">
  <div class="col-xs-8 col-sm-4 col-md-3 col-lg-5  box-background" ng-repeat="post in posts">
    <div class="col-md-4 img-space">
      <img class="img-circle" alt="Bootstrap Image Preview" src="{{prov.picture}}" /></div>
    <div class="col-md-4">
      <h4>{{post.author}}</h4>
      <p class="text-grey">
        {{post.content}}
      </p>
    </div>
    <a ui-sref="posts/:id" class="btn btn-primary btn-color" style="width:100%">View details</a>
  </div>
</div>

Looking for a simple solution without using a traditional MVC pattern as I'm used to working with a mongoose and node backend. Any suggestions or ideas are greatly appreciated. Thank you!

Answer №1

To retrieve the id from your route and incorporate it as a variable in your $http request URL, utilize $routeParams. This way, when fetching the identical sourse.json file, you can employ that id to exclusively link the accurate post to your view variable.

Explore more about $routeParams here

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

The issue of accessing the session before scripts are loaded arises when using VueJS alongside Firebase Authentication

Currently grappling with a project where I'm facing some challenges... I've opted for VueJS on the frontend and implemented Firebase Authentication for user login. I'm trying to determine the login status of a user by using firebase.auth(). ...

Ways to retrieve the body from a Ruby on Rails request

I attempted to make a Postman request to the following endpoint using this body: { "username" : "Sebastiansantander", "password" : "1233342" } Even though I tried using params.permit[:username,:password], I e ...

Modify the text tone within a specific cell

Welcome to my unique webpage where I have implemented a special feature. The text highlighted in red represents the unique identifier for each individual cell. Interestingly, below there is an input field containing the code "0099CC", which corresponds to ...

Arrange individuals using AngularJS into an alphabetical directory and apply filtering

Within my AngularJS application, I have an object where keys represent letters of the alphabet and each key contains an array of people. <div ng-repeat="(letter, group) in people"></div> <div ng-repeat="people in letter"></div> ...

Tricks for prompting Angular2 to recreate components every time they are displayed

Within our angular2 Typescript application, the functionality of our components is heavily reliant on the parameters they receive from the router, resulting in dynamic behavior based on these inputs. The current stage of development for the application is ...

Making Monaco compatible with the integration of Vuejs and electron

I am intrigued by the idea of integrating the Monaco editor into a Vue.js backed Electron project. So far, I have successfully run Microsoft's Electron sample for the Monaco editor. There are several npm repositories for vue.js and monaco, but none o ...

How can a string be formatted based on a dictionary or JSON object in Python?

I am facing an issue with a JSON file that I have converted to a Dict. The dict looks something like this: { "a": "1", "b": "2", "c": "3" } Now, I need to format a string based on the values ...

Debugging issue with Mongoose find search in ExpressJS with an if statement

Welcome to our URL shortener project! app.get('/:url', (req,res) => { Url.find({userUrl:req.params.url},(err,doc)=>{ //checking if the link is already in the database if(err){ console.error(err) }else if(doc[0].userUrl==req ...

Validating arrays in Laravel through iterations

I used JavaScript to send an array from my form, where the values are collected from various input fields and stored in a single variable. <input type="hidden" name="details" id="details"> JavaScript Code: document.querySelectorAll('form&apos ...

Text centered vertically with jQuery is only loaded after the page is resized

My jQuery script is designed to vertically center text next to an image, but it seems to only work properly after resizing the page. $(window).load(function () { $(function () { var adjustHeight = function () { $('.vertical-al ...

What is the best way to insert dynamic data into a modal?

I am currently facing an issue with passing a dynamic scope variable into a modal window. The problem arises when I try to update the variable while the modal is open. At present, I send the data to a controller when the modal opens: scope.open = func ...

What causes the issue - Uncaught SyntaxError: The specified module '/src/router/index.js' does not have an export named 'default' in main.js of vue?

When using Vite with Vue, I encountered an error - Why am I getting the error message "Uncaught SyntaxError: The requested module '/src/router/index.js' does not provide an export named 'default'" in my main.js file? What could be causi ...

How can REGEX be used to extract the ID at the end of a URL excluding the forward slash

Struggling with a GreaseMonkey script and need help with a REGEX to extract the ID from a URL of an article. Here is an example URL: I want to extract the ID at the end after the comma: 272317 I tried using this REGEX: (,([\d]+)) to only capture di ...

Anomalous Snackbar and Alert Interactions

Why am I getting an error with this code snippet: import Snackbar from "@mui/material/Snackbar"; import MuiAlert from "@mui/material/Alert"; const Alert = ({children}) => <MuiAlert>{children}</MuiAlert> <Snackbar ope ...

Transfer of table data from view to controller encountering issues

I am attempting to send the information from my dynamically populated table to the controller. <tbody> @if (ViewBag.data != null) { foreach (var ...

Using Ajax to send a button click to a PHP script, which in turn communicates with a serial device

I've been attempting to use a button to trigger a function on a serial device (an Arduino) through ajax and php, but I'm struggling to make it work. Below is my HTML: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.m ...

When using the same controller with two divs, the model does not appear to be updated

After assigning the same controller to two different divs, I noticed that the model being updated in one div is not reflected in the other. <body ng-app="myApp"> <div ng-controller="filterCtrl"> <p ng-bind="test" /> < ...

Understanding the process of configuring Quasar Language in SSR Mode using route parameters

Is there a way to incorporate Quasar Language Packs while utilizing this specific routing method and SSR mode? const routes = [ { path: '/:locale?', beforeEnter: localeNavGuard, children: [ ... ] } ] ...

Adjust the minimum date of the second datepicker to be one day after the selected date from the first datepicker

I am currently using Materializecss and working on developing a hotel reservation system. My goal is to have the DateOut Datepicker's minimum date set to 1 day ahead of the selected date in the DateIn Datepicker. Initially, this functionality works as ...

Updating values in an Object by assigning them with results from an array

I've been grappling with a data structure issue in nodejs and I could really use some assistance. Here's the scenario: I have an object: let obj = { commenter: '', comment: '', numberOflikes: 0, } Along with a containe ...