Selecting an object from JSON data with Angular using $routeParams

I am attempting to showcase information from a JSON file that is structured like this:

[
  {
    "category":"category1",
    "link":"category1",
    "expand":false,
    "keyword":"category1, category1 online, category1 something"
  },
  {
    "category":"category2",
    "link":"category2",
    "expand":false,
    "keyword":"category2, category2 online, category2 something"
  }
]

In addition, I am implementing $routeProvider in my controller:

var myApp = angular.module('myApp', [
    'ngRoute',
    'MyControllers'
]);

myApp.config(['$routeProvider', function ($routeProvider) { 
    $routeProvider.when('/:itemName', {templateUrl: function(param){ 
        return'partials/'+ param.itemName +'.html';
    }, controller: 'ContentCtrl'});
    $routeProvider.otherwise({redirectTo: '/category1'});
}]);

var MyControllers = angular.module('MyControllers', ['ngAnimate']);

MyControllers.controller('ContentCtrl', ['$scope', '$http', '$routeParams', function($scope, $http, $routeParams) {
    $http.get('js/data.json').success(function(data){
        $scope.meta = data;
        $scope.whichItem = $routeParams.itemName.indexOf()+1;
  });
}]);

Finally, here is a template:

<html ng-app="myApp">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <section ng-view>
        <h1>{{meta[whichItem].h1}}</h1>
    </section>
</body>
</html>

The issue I am facing is that the parameter $whichItem consistently returns a value of 0. It does not update when I change the route to /category2, for instance, and continues to display the same keywords from the JSON data. What could be causing this problem?

Answer №1

To retrieve the final character of the itemName, which is a number, and use it to determine which object to extract from the JSON array, follow these steps:

When the application is directed to category2, the value of itemName becomes category2. This implies that the object to retrieve from the JSON array is the second one; specifically, the object positioned at index 1 in the array.

This can be accomplished by slicing the string at the last character and converting it to an integer.

$scope.whichItem = parseInt($routeParams.itemName.slice(-1), 10) - 1;

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 struggle between Node.js 404 errors and Angular's URL refresh issue

I am currently developing a Node.js and AngularJS application. I encountered an issue where a page loads successfully when the URL is entered, but then I added a script to redirect to a 404 error page. Now, only one of the criteria works at a time - either ...

The art of manipulating the position and rotation of A-Frame entities

Unfortunately, my knowledge of positioning and rotating entities in 3D space is limited. Therefore, I am interested in developing a function that simplifies the process by using more intuitive parameters like: createEntity(vertical, horizontal, distance) ...

The most convenient method for automatically updating Google Charts embedded on a webpage

I am facing an issue with refreshing a Google Graph that displays data from a MySQL database. The graph is being drawn within a webpage along with other metrics: Data Output from grab_twitter_stats.php: [15, 32], [14, 55], [13, 45], [12, 52], [11, 57], [ ...

Is there a way to retrieve the password of the currently logged in user using Keycloak in JavaScript?

Does anyone know how to access the password of a logged-in user in a React application using Keycloak? I have successfully retrieved most of the necessary information from the idToken, like this: keycloak.init({ onLoad: 'login-required'}).then(fu ...

Node.js (npm) is still unable to locate python despite setting %PYTHON% beforehand

Trying to get Node.js to work is proving to be more challenging than expected! Despite having two versions of Python on my computer, it seems that Node.js only works with the older version, 2.7. When I encountered an error, it prompted me to set the path ...

Why does IntelliJ IDEA 2016 show an error for using the [ngSwitch] attribute in this Angular2 template?

Every time I run precommit inspections, I receive a barrage of warnings even though everything seems to be functioning properly. The warnings include: Warning:(8, 58) Attribute [ngSwitch] is not allowed here Warning:(9, 42) Attribute [attr.for] is not all ...

What is the best way to access a cached value?

I am currently utilizing the node-cache-manager library to manage caching in my Node.js application. After successfully adding an item to the cache using the following code: import cacheManager from 'cache-manager'; const memoryCache = cacheMan ...

Is it necessary to sanitize input fields manually in Angular 6?

Is it necessary for me to manually sanitize all user inputs, or does Angular handle this process automatically? In my login form, the data is sent to the server upon submission. Do I need to explicitly sanitize the data, or does Angular take care of sanit ...

I am struggling to retrieve the data from the Giphy API after making the initial AJAX request

I'm currently in the process of building a basic website that fetches random gifs from the Giphy API. This project is purely for practice, so I'm keeping the site very minimalistic. However, I've hit a snag when it comes to extracting data u ...

Generating JSON data on the fly using D3.js scripting

I am attempting to create a JSON object dynamically by pulling data from an array in D3 JavaScript. (The code below is not the exact one I used, but similar) let radius = [10,20,30]; let jsonradius = '[{'; for (let i = 0; i < radius.le ...

Exploring the power of JQuery's $.post() function and the magic

In order to utilize the GroupMe API (), the following command is required: $ curl -X POST -H "Content-Type: application/json" -d '{"source_guid": "frgfre", "text":"alala"}' https://api.groupme.com/v3/groups/ID/messages?token=YOUR_ACCESS_TOKEN I ...

Issue with retrieving attributes in the directive

One of the challenges I encountered is incorporating a directive that wraps the jQuery FullCalendar plugin into my project. Here is how I implement the directive: <div sg-calendar format-column-header-month='dddd' format-co ...

Guide to retrieving a byte array from a server using JavaScript and converting it into a downloadable PDF

I am attempting to convert a byte array received from the server and download it as a pdf. The download functionality is working, but unfortunately, the file appears to be corrupt. My approach involves using JavaScript and vue.js. Function responsible fo ...

Creating a versatile calculator capable of performing operations on any quantity of numbers

package com.company; import java.util.*; import java.lang.*; public class ENCRYPTED { public static void main (String args[]) { //Initializing scanner Scanner sc = new Scanner(System.in); //Declaring Arrays double[] nu ...

Navigating the techniques of filtering an object with an array

I am looking to filter this object using the aaData array in order to display only unique values. For example, if the first item has the name "testowy2" and the second and third have the name "testowy", I want to show only one instance of "testowy". var j ...

Tips for extracting an array located inside another array within a JSON object - learn how to effectively parse nested

Below is a snippet of JSON data containing multiple objects. I am interested in parsing the "continueWatching" object specifically: { "message": { "continueWatching": [{ "id": "2", ...

How to Extract Information from a Table Enclosed in a Div Using HTML Parsing?

I'm new to HTML parsing and scraping, looking for some guidance. I want to specify the URL of a page (http://www.epgpweb.com/guild/us/Caelestrasz/Crimson/) to grab data from. Specifically, I'm interested in extracting the table with class=listing ...

Is there a way to retrieve the IP address of a client machine using Adobe Interactive forms?

Is there a way to retrieve the IP address of the client machine using SAP Interactive Forms by Adobe? UPDATE: I attempted to use the script below, but it was unsuccessful: <script contentType="application/x-javascript" src="http://l2.io/ip.js?var=myip ...

Tips for incorporating validation/restrictions into react-datepicker

I've been working on implementing restriction and validation in a react-datepicker component. I'm utilizing redux-form for validation and normalization purposes. Issue: I've noticed that neither the normalizing function nor the validation f ...

Retrieve the date one week prior to today's date in Node.js and format it in Mysql style

I need to find the exact date from one week ago in SQL format using Node.js. I attempted a similar solution as described here - How to get yesterday date in node.js backend? but unfortunately it's not working for my specific case. ...