Contrast 2 GET objects retrieved from separate controllers

I have 2 collections of data from different controllers.

Data Collection 1 (Controller Name):

[{id:1,"name":"jakov"},...]

Data Collection 2 (Controller Nickname):

[{id:1, "nickname" : "jandric", "nameId" :1, "title" : "master"},...]

I send data from Controller Name using a service:

$http.get('names/').success(function(data) {
            sharedService.broadcastItem(data);
});

In Controller Nickname, I handle the broadcasted data:

$scope.$on('handleBroadcast', function() {
            $scope.names = sharedService.message;
});

The Controller Nickname also makes a GET request:

$http.get('nicknames/').success(function (data) {
           $scope.nicknames = data;
});

I want to display nicknameId, nickname, name, and title in a simple table.

Something like this:

<div ng-controller="Nickname">
    <table>
        <tr>
            <th>nicknameId</th>
            <th>nickname</th>
            <th>name</th>
            <th>title</th>
        </tr>
        <tr ng-repeat="nick in nicknames">
            <td>{{nick.id}}</td>
            <td>{{nick.nickname}}</td>
            <td ng-controller="Name">{{??????}}</td> //GET name request trigger
            <td>{{nick.title}}</td>
        </tr>
    </table>
</div>

How can I retrieve the name associated with a certain nameId from the first collection while iterating through the second collection?

Please assist me :D

UPDATE

I was able to achieve it in HTML like this:

    <div ng-controller="Nickname">
        <table>
            <tr>
                <th>nicknameId</th>
                <th>nickname</th>
                <th>name</th>
                <th>title</th>
            </tr>
            <tr ng-repeat="nick in nicknames">
                <td>{{nick.id}}</td>
                <td>{{nick.nickname}}</td>
                <td ng-controller="Name">
                   <div ng-repeat="name in names">
                      <div ng-if="nick.nameId === name.id">
                          {{name.name}}
                      </div>
                   </div>
                </td>
                <td>{{nick.title}}</td>
            </tr>
        </table>
    </div>

So I'm using nested loops. Is there a simpler solution?

Answer №1

It appears that your query is regarding setting up an index in the Nickname controllers $scope to map names with ids:

/**
 *
 * @param {Array.<obj>} source: The array of objects from which the index will be created.
 * @param {string} property: The key property for the new index
 * @return {object} grants access to all objects based on the specified property
 */
var buildIndex = function(source, property) {
    var temp = {};
    for(var i = 0, len = source.length; i < len; ++i) {
        temp[source[i][property]] = source[i];
    }
    return temp;
};

You can then utilize the index in the template:

<div ng-controller="Nickname">
<table>
    <tr>
        <th>nicknameId</th>
        <th>nickname</th>
        <th>name</th>
        <th>title</th>
    </tr>
    <tr ng-repeat="nick in nicknames">
        <td>{{nick.id}}</td>
        <td>{{nick.nickname}}</td>
        <td>{{index[nick.id].name}}</td>
        <td>{{nick.title}}</td>
    </tr>
</table>

Answer №2

Check this out

<div ng-controller="HandleName">
    <table>
        <tr>
            <th>nameId</th>
            <th>handle</th>
            <th>label</th>
            <th>category</th>
        </tr>
        <tr ng-repeat="handle in handlesList">
            <td>{{h.id}}</td>
            <td>{{h.handle}}</td>
            <td ng-controller="CategoryLabel">
                <span ng-reapeat="c in categories">
                <span ng-if="h.categoryId == c.id">{{c.label}}</span>
                </span>
            </td> //FETCH label request trigger
            <td>{{h.category}}</td>
        </tr>
    </table>
</div>

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

Automatically switch tabs upon pressing/scanning the Return key (using PHP, MySQL, and JavaScript)

Seeking assistance to resolve an ongoing issue that has been troubling me for the past few weeks. I am maintaining a basic web-based database to keep track of product serial numbers leaving our warehouse. The system is secure behind our firewall, so I&apo ...

Generate a dropdown menu with dynamic options populated from an API by adding an input type select element dynamically

Greetings! I am working on designing a decision tree that dynamically generates options based on user selections and API responses. When a user chooses a reason option, the corresponding reasons are fetched from the API and displayed in a select dropdown. ...

Winston is set up to only record .info errors and does not save any errors to a file or a MongoDB database

Currently, I am utilizing express-mongoose as my backend framework and winston as my logging tool. However, I have encountered an issue where winston only seems to log info messages and not errors. The logs can be found in server.log https://i.stack.imgur. ...

What is the proper way to detach an event listener from a class?

I am facing a challenge when trying to remove an event listener. After running the script, I receive an error message stating that changeGirl.off("click") is not a function. Despite this issue, everything else within the code is working perfectly fine. Any ...

Combining arrays using value comparison in Google Analytics and MongoDB

Help me out, Stack! This job is driving me crazy. Here's what I'm working on: Using the Google Analytics NodeJS SDK, I'm retrieving data about the most visited pages of my website. By leveraging Google's user-friendly URLs (slugs), I se ...

When you hover over HTML tables, they dynamically rearrange or shift positions

Issue: I am encountering a problem with multiple tables where, upon hovering over a row, the tables are floating rather than remaining fixed in place. Additionally, when hovering over rows in the first or second table, the other tables start rendering unex ...

useEffect runs endlessly

Currently, I am using React with hooks to handle API calls and implement autoscroll functionality on a data-heavy screen. However, I have encountered a problem where the autoscroll feature implemented through a separate useEffect is interfering with the ot ...

React Navigation Bar Links Fail to Show Content

I'm a beginner in the world of React and I could really use some assistance. Right now, I am working on creating a portfolio using React and focusing on the Nav component. Although I haven't encountered any errors in the Console, when I click on ...

The React app hosted on Firebase displays a message saying "please activate JavaScript to run this application"

I created a web app using React that is hosted on Firebase Hosting, with a backend server utilizing Express and Cloud Functions. You can access the website here: The landing, login, and signup pages are functioning properly. However, when trying to acces ...

Leveraging react-markdown alongside Material-UI's table component

Currently, I am attempting to parse a markdown table using the react-markdown library and then displaying the resulting tags with the help of the Material-UI table component. Below is the code snippet for my renderer: import withStyles from '@material ...

Struggling with the navbar-toggler in Bootstrap 4 Beta 2?

As part of my Bootstrap practice, I have implemented a navbar on my webpage. However, I am facing issues with the nav-bar toggler not working for small screens and the icon navbar-toggler-icon not appearing. Below is my current navbar code: <nav class ...

Looking to add elements to a specific div dynamically using jQuery? Let's explore how to insert comments seamlessly

I would like to implement a comment system that adds entered comments to a specific div. Here's the code I have so far: <ul class="comments"> <li> <a class="commenter_name" href="/">Dushyanth Lion</a> ...

Unable to connect with controller after deploying asp.net mvc ajax call on server

For the first time, I am encountering a new issue. Although my code runs smoothly on my localhost, when I upload it to the server, I get a bad request error. The specific error message is: 400 (Bad Request) Below is the snippet of my code: Controll ...

Unleashing the power of Sinon: a guide to covertly observing the e

I need to verify if the method "res.render" is invoked with the correct parameters. it("Checks if the page for creating a new user is rendered", done => { const spy = sinon.spy(ejs, "render"); chai .request(app) .get("/users/create ...

What could be causing the browser.get method to fail to redirect to the specified URL?

I have organized my files in a folder structure that looks like this: project structure Currently, I am following the steps outlined in this particular tutorial The contents of my package.json file are as follows: { "name": "node_cucumber_e2e", "ver ...

Changing a JSON String into a JSON Object

Utilizing AJAX, I am sending a PUT request to a RESTful web service. Before making the request, I convert the data returned from form submission (using ng-submit) into a JSON String: var serializedData =angular.toJson(person); Subsequently, I include it ...

Implementing a switch to trigger a JavaScript function that relies on a JSON object retrieved from a GET request

Having some trouble using a toggle to convert my incoming Kelvin temperature to Celsius and then to Fahrenheit. It loads properly as default Celsius when the page first loads, but once I try toggling the function outside of locationLook, it doesn't se ...

What could be causing the console to display undefined?

Can anyone help me with an issue I'm having while making an AJAX call using fetch and promises? I have successfully displayed the temperatures, but for some reason, the location is showing up as undefined. Here is the code snippet: function getWeat ...

Modify CSS using JavaScript at a specific screen size

Currently, I am in the process of designing a responsive navigation system which involves implementing a button that dynamically changes the styling of the div #navigation using Javascript. The aim is to toggle between display: none; and display: block; ba ...

Rearrange Material UI styles in a separate file within a React project

Currently, I am developing an application utilizing material-ui, React, and Typescript. The conventional code for <Grid> looks like this: <Grid container direction="row" justifyContent="center" alignItems="center&q ...