How to Retrieve JSON Object Using Dynamically Generated String in Angular

Creating a controller in Angular involves retrieving URL parts and parameters using $statePrams.

The $http service is then called to retrieve data from a JSON file. Once the data is received, the content of a specific object element - determined by $stateParams - is assigned to a $scope variable. This variable can be manipulated in the view to generate an unordered list.

An issue arises when trying to access a dynamically generated path like

result['data']['datas']['timeline']
, resulting in an ngRepeat:dupe error.

If I manually specify the assignment as

$scope.naviData = result['data']['datas']['timeline'];
, it works fine and displays the desired data as list elements in the view.

To address this problem and achieve dynamic object element access without errors, two screenshots are provided:

First screenshot shows manual input: https://i.stack.imgur.com/NamCA.png

Second screenshot demonstrates generated variable usage: https://i.stack.imgur.com/yEVad.png

In both cases, the first console.info output displays the state parameters used to construct the path. Below are snippets of code responsible for handling these dynamic operations.

angular.module('MPWeb.datas', [])
  .controller('DataDetailsCtrl', function($scope, $state, $stateParams, $http) {
    // code block here
  });

Utilizing track by $index in the view results in the generation of list elements based on the characters of the constructed path.

Answer №1

The issue arises when using trackby in the ng-repeat directive within your template. It is important to note that trackby requires unique keys from the objects in the array.

For example:

values = [{id:12,name:'king'},{id:13:name :'ram'},{id:14:name:'king'}]

Correct Usage:

<div ng-repeat="value in values  track by id">
{{value.name}} : {{value.id}}
</div>

Another Correct Example:

<div ng-repeat="value in values  track by $index">
{{value.name}} : {{value.id}}
</div>

Incorrect Usage:

<div ng-repeat="value in values  track by name">
{{value.name}} : {{value.id}}
</div>

Answer №2

After spending some time grappling with it, I finally managed to figure out the solution with a little assistance. For those who may encounter this issue in the future, here is how you can resolve it within the controller:

  $scope.params = $stateParams;
  $scope.navPrefix = $state.current.url.split('/:')[0];
  $scope.navPrefix = ($scope.params.categoryId) ? $scope.navPrefix + '/' + $scope.params.categoryId + '/' : $scope.navPrefix + '/';
  $scope.activeItem = ($scope.params.articleId) ? $scope.params.articleId : $scope.params.categoryId;
  var tempCat = $state.current.url.substr(1);
  $scope.naviCat = tempCat.split('/:')[0];
  // set data for dynamic object handling
  var base = $scope.naviCat;
  ...
  // generate sideNavigation
  $http({
    method: 'GET',
    url: './json/mp-navigation.json'
  }).then(function successCallback(result, status, headers) {
    var naviMain = result.data[$scope.naviCat]['main'];
    var naviTemp = result.data[stateConfig.params.prefix][stateConfig.params.categoryId];
    $scope.naviData = (stateConfig.params.categoryId == '') ? naviMain : naviTemp;
    }, function errorCallback(result, status, headers) {
      console.warn(status + ' encountered while trying to retrieve: ' + headers);
  });

Cheers

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

Steps to eliminate a specific value from an array

I need to remove values with the .html extension from an array in JavaScript, leaving only those items that do not have the .html extension. Here's my current code: main.js: var arr=["test1.html","power.html","main.html","save.md","kart.html","taste ...

Following the path of JavaScript function calls

As I explore my Chrome console, I find myself puzzled by the mystery of the JavaScript file that gets called when I import a file from my computer after clicking on an input file tag. It seems to happen without any clear indication of which method triggere ...

The directive in Angular compels the webpage to carry out the added HTML attribute

There is a custom directive in my code that applies the spellcheck attribute to two div elements as shown below: (function(){ 'use strict'; app.directive('spellchecker', spellchecker); spellchecker.$inject = ['$timeout&a ...

Transforming a JSON array into FormData results in a string representation

When I convert JSON data into Form data in my React app and send it to the server, the arrays and objects are being converted into strings on the server end. var formdata = new FormData(); for (let i = 0; i < images.length; i++) { formdata.append( ...

Transferring data between components in React by passing parameters through Links

When calling another component like <A x={y}/>, we can then access props.x inside component A. However, in the case of calling EditCertificate, the id needs to be passed to the component. I am using a Link here and struggling to pass the id successf ...

Tips for creating an effective planar reflection using Open Graphics Library (OGL) in conjunction with a perspective camera

I'm attempting to create a mirror-like reflection of a WebGL scene on a plane using ogl, similar to how a mirror would behave. I tried implementing a basic version of the three.js reflector but ended up with a distorted image that doesn't accurat ...

pressing the downward arrow does not cause the number to decrease

I'm facing an issue with my code in this video. The increment is working when the upward arrow is clicked, but not the decrement. I suspect there's a problem with the jQuery code. Initially, I tried modifying from top to bottom, and changing +1 t ...

A guide on retrieving information from a database with PHP and transferring it to Javascript

As I work on creating a website using HTML, CSS, MySQL, and JavaScript, my goal is to allow users to log in and engage in a quiz with 40 questions. Below is the JavaScript code for a countdown timer that includes the "questions" variable. After 40 seconds ...

Learn how to toggle between two different image sources with a single click event in JavaScript

If the button is clicked, I want to change the image source to one thing. If it's clicked again, it should change back to what it was before. It's almost like a toggle effect controlled by the button. I've attempted some code that didn&apos ...

What is causing ngdocs to produce zero files?

I have created a basic project to experiment with grunt-ngdocs (https://www.npmjs.org/package/grunt-ngdocs). But, for some reason, when I attempt to generate documentation, it fails to recognize any comments. Why is this happening? Can someone offer assist ...

Tips for formatting the JSON date format in a Spring Boot application

I'm currently working on setting up a rest service using Spring Boot and Gradle. My goal is to format the JSON date in the "yyyy-MM-dd" form, specifically for the dateOfBirth field to be displayed as "16-03-2015". However, I'm running into an iss ...

Retrieving data from a JSON file depending on the selection made by the user in a dropdown menu

In my project, I have a JSON file named countries.json that contains country and regional information. Users are required to select a country using a Python-generated dropdown list from this file. However, due to the backend nature of Python, I am unable t ...

What is the reason behind material-ui's decision to invoke their dialogs twice?

After attempting to implement a modal and realizing the strange behavior, I switched to using a dialog instead. To my surprise, the issue persisted. This is how I approached it: import Dialog, { DialogProps } from '@material-ui/core/Dialog'; imp ...

Persistently Undefined Angular Attribute

I have been trying to dynamically bind a CSS class using an AngularJS function. While the functionality is working properly, I keep encountering numerous errors in the browser console. Can anyone offer assistance with this issue? I have included my code an ...

Using Angular JS to redirect to a CodeIgniter controller involves utilizing the routing capabilities of Angular

Currently, I am implementing CodeIgniter controller functions (example). <?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Me extends CI_Controller { public function __construct() { ...

Generating dynamic dropdown menus using data from a database with the help of PHP and Ajax technologies

I'm currently working on creating a dynamic dropdown menu that will be populated with data retrieved from a database. I've hit a roadblock in parsing the data from a multidimensional array sent by a PHP file. Here's a snippet of my code: Se ...

Using Ajax to append form data to JSON is more efficient than using PHP alone

I am new to JavaScript and have never worked with PHP before. After spending hours on Stack Overflow, I managed to piece together this code snippet. My goal is to create a simple form with a few fields that will be saved into a JSON file. Each new entry sh ...

What is the method for defining an Angular directive within the link function of another directive?

I am in the process of developing a unique server-validate directive that verifies form input asynchronously by sending a partial form to our server backend for validation and analyzing the response. I envision using it in this manner: <input type="tex ...

Can the Twitter Bootstrap typeahead feature be used with an external data source?

Can the typeahead feature in version 2.0.3 of twitter-bootstrap work with a remote data source? You can check out the link for more information on the typeahead functionality: ...

"Automate the process of manual content duplication with JavaScript's for each replacement

Seeking a solution to automate the selection process without writing individual JS scripts for every input. For instance, having 10 double inputs (total of 20 inputs) and utilizing the each() function or other methods by only declaring selectors. Find th ...