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>