Utilizing AngularJS to retrieve and showcase information from a single post through the WordPress API

Utilizing the WordPress API as a data source for an AngularJS/Ionic application, I have a post type named programmes. The JSON structure of the programmes includes:

var programmes = [
 {
  id: 6,
  title: "A post",
  slug: "a-post"
 },
 {
  id: 7,
  title: "Another post",
  slug: "another-post"
 },
 {
  id: 8,
  title: "Post 123",
  slug: "post-123"
 }
]

I've successfully displayed the list of programmes using ngRepeat. However, I am facing difficulty retrieving data for an individual post.

My attempt to access data for a single programme like this:

var programme = programmes[$stateParams.programmeId];
presents an issue. For instance, when clicking on the first "A post," it returns 6 as the programme ID which does not correspond to the index of the object (which is 0).

How can I fetch data from a single programme when the ID and index do not align without manually resetting the programme IDs in the database?

Below are the files I have worked on thus far:

app.js

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

  .state('app', {
    url: "/app",
    abstract: true,
    templateUrl: "templates/menu.html",
    controller: 'AppCtrl'
  })

  .state('app.programmes', {
    url: "/programmes",
    views: {
      'menuContent': {
        templateUrl: "templates/programmes.html",
        controller: 'ProgrammesCtrl'
      }
    }
  })

  .state('app.programme', {
    url: "/programmes/:programmeSlug",
    views: {
      'menuContent': {
        templateUrl: "templates/programme.html",
        controller: 'ProgrammeCtrl'
      }
    }
  })
  $urlRouterProvider.otherwise('/app/programmes');
});

data.js

.factory('DataFactory', function($http) {

  var urlBase = 'http://event-app.dev/wp-json/wp/v2';
  var APIdata = {};

  var currentProgramme = null;

  return {
    getProgrammes: function() {
      return $http.get(urlBase + '/programmes');
    }
  }
})

controllers.js

.controller ('ProgrammesCtrl', function ($scope, DataFactory) {
  getProgrammes();
  function getProgrammes() {
    DataFactory.getProgrammes().then(function(response) {  
      $scope.programmes = response.data;
    }, 
    function(error) {
      $scope.status = 'Unable to load data';
    });
  }
})

.controller ('ProgrammeCtrl', function ($scope, $stateParams, DataFactory) {
  getProgrammes();
  function getProgrammes() {
    DataFactory.getProgrammes().then(function(response, id) { 
      var programmes = response.data;
      $scope.programme = programmes[$stateParams.programmeId];

    }, 
    function(error) {
      $scope.status = 'Unable to load data';
    });
  }
})

programme.html (view to display a single programme)

<ion-view view-title="{{programme.title}}">
  <ion-content>
    <ion-list>
      <ion-item>
        {{programme.title}}
      </ion-item>
    </ion-list>
  </ion-content>
</ion-view>

Answer №1

If you're looking to retrieve a specific program from the `programs` array, you can achieve this by implementing a simple loop. Take a look at the updated `fetchPrograms()` function below:

 function fetchPrograms() {
            DataService.retrievePrograms().then(function (response) {
                    var programsList = response.data;
                    for (var j = 0; j < programsList.length; j++) {
                        if (programsList[j].id === $stateParams.programId) {
                            $scope.selectedProgram = programsList[j];
                            break;
                        }
                    }
                },
                function (error) {
                    $scope.errorMsg = 'Failed to fetch 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

Create a function to produce a list of dates within two specified date ranges using JavaScript

Looking for assistance as a beginner in JavaScript. Can anyone guide me on how to generate a list of dates between dateA and dateB? For instance: dateA = 07/01/2013 dateB = 07/01/2014 Desired outcome: 07/01/2013, 07/02/2013, 07/03/2013, 07/04/2013...a ...

Can a single button click be shared across multiple forms?

The main concept involves a grid where when a user double-clicks on a row, a modal window (Bootstrap panel) opens with a panel-body section for editing the data and a panel-footer containing a btn-group for actions like "Save", "Cancel", or "Close". This s ...

Encountered an issue with locating the module 'webpack-cli/bin/config-yargs' while attempting to run webpack-dev

Encountering an error while trying to start the webpack dev server with the command provided below. Despite suggestions that it could be due to outdated webpack versions, I am confident that all components are up to date: [email protected] [email ...

What is the best way to smoothly scroll to another page using a specific id?

My website consists of multiple pages and I am looking for a code that will allow for smooth scrolling navigation to another page when loading on a specific id or section. For example, in the navbar I have multiple pages with links. When clicking on a lin ...

What is the process for integrating an autoplay script into Turn.Js?

Can someone guide me on how to implement this code in Turn.Js? setInterval(function() { $('#flipbook').turn('next'); }, 1000); ...

What advantages does using an RxJS Subject have over handling multiple event listeners individually in terms of speed

After investigating a page's slow performance, I identified an angular directive as the root cause. The culprit was a piece of code that registered event listeners on the window keydown event multiple times: @HostListener('window:keydown', ...

Using NextJS getServerSideProps to Transfer Data to Page Component

Having trouble with my JavaScript/NextJS code, and not being an expert in these technologies. I'm using the method export const getServerSideProps: GetServerSideProps = async () => {} to fetch data from an integrated API within NextJS. The code mig ...

Firestore query is returning empty results upon page initialization, but provides data upon subsequent re-renders in React Native

ISSUE I'm encountering an issue where I am unable to fetch documents from a Firestore collection when the page loads. Despite executing the query multiple times during loading, it does not return any results. However, if I trigger the query by changi ...

VueJS's approach to routing through modular components

I am currently working on a website where I need to set up different category pages using dynamic routes. To achieve this, I am utilizing vue-router and aiming for a single dynamic route that can switch between pages by loading different components. Here ...

Utilizing jspm for installing npm packages along with their dependencies

When using jspm, I can easily install npm packages by running: jspm install npm:<pkg-name>. This allows me to use the package in development, like so: import myPackage from 'myPackage';. If the package.json file of the npm package includes ...

Deferred computed property fails to recognize the final character entered into the input field

I am facing an issue with my automated tests using selenium. The problem lies with a particular input field in a web form: <input data-bind="value: searchText, valueUpdate: 'afterkeydown'"></input> Here is the model associated with ...

Manipulating the content of a specific row's table cells with a text box in jQuery Datatables

I am working with a jQuery datatable that consists of only one column. Every time a row is selected, a panel opens with a text box that automatically populates with the name of the selected td. I am trying to figure out how to edit the name of the selected ...

Executing a npm script (script.js) with custom arguments - a step-by-step guide

I'm considering creating a setup similar to lodash custom builds. Basically, I want to allow users to input a command like: lodash category=collection,function This would create a custom module with the specified category. I've been looking in ...

Placing a div tag directly beneath another div tag

Imagine you have a div element with the class name divstudent, let's call this one div1. Now, you want to dynamically create another div element below div1, but outside of it using JavaScript. How can you achieve this? "div1" <div class="divstuden ...

When Ajax responseText and echo fail, the header file contents are sent back instead

I have a section of code in my PHP file called thePhpFile.php that is used to handle an Ajax call: <?php require_once('usefulStuff.php'); // includes useful functions if (isset($_GET['zer'])) { $bFound = false; if(! $bF ...

Slider Jquery - Displaying Half-Step Visual Bar Lengths

JSFIDDLE $(function() { $( "#slider-range-min" ).slider({ range: "min", value: 5, min: 0, step: .5, max: 10, slide: function( event, ui ) { $( "#amount" ).val(ui.value); ...

Error: Unable to instantiate a THREE.Scene object in Three.js due to TypeError

Recently, I decided to experiment with Three.js in order to incorporate it into a project of mine. However, upon running the initial example provided in the documentation: <html> <head> <title>My first Three.js app</title& ...

Enhancing User Experience with JQuery Pagination and Efficient Data Loading

I am looking to implement pagination for data retrieved from a database. The information needs to be displayed in a 4x4 table format. For the remaining data that doesn't fit in the initial view, I want to enable pagination with AJAX functionality so ...

A guide on using Material UI - InputLabel in JavaScript

I'm currently integrating a form from this Codepen link into my project built with Codeigniter. However, I am encountering issues after incorporating material-ui into the CodeIgniter framework. The problems I am facing include an invalid token and an ...

Creating a compact array from a larger array in JavaScript

I am currently using the jquery.bracket library and I am looking to split a large array into pairs like ["'Team 1', 'Team 2'"],["'Team 3', 'Team 4'"] from var all= ["'Team 1', 'Team 2'","'T ...