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

Tips for adjusting image size to take up only half of the screen in NextJS

Struggling to resize an image to fit only 50% of the screen in NextJS? The Image component provided by NextJS comes with its own inline styling, making it tricky to customize. Currently, I attempt to style the image by wrapping the Image component in a spa ...

A method to trigger the opening of a div tag when a button is clicked using Vue.js

<div class="input-wrapper"> <div class="mobile-icon"></div> <input class="input-section label-set" type="text" v-model.trim="$v.mobile.$model" :class="{'is-invalid': ...

Issues with single and double quotation marks in JQuery

I'm having trouble inserting a tag into the page. The tag contains both single and double quotes, so I tried storing that part in a variable named content. Can someone explain why this content variable isn't displaying onclick after the code runs ...

Save JSON data in an HTML document or vice versa

Hey there, the title of this post might seem a bit unclear but I couldn't think of another way to phrase it. So here's the dilemma: I have some data that is JSON encoded and stored in a .json file: {"foo":"bar", "bar":"foo", "far":"boo"} Additi ...

Changing global variables within a POST request

I am currently developing a quiz application for the Noops Challenge on Github, utilizing the Fizzbot API available at Noops Challenge. To keep track of the current question and the next question URLs, I have defined global variables to store and assemble ...

Is the routing malfunctioning and causing the page to appear blank?

I am currently attempting to implement routing in the code below. Despite changes in the URL, the page remains empty and there are no errors shown in the console. html <div ng-app="myApp"> <ul> <li><a href="#!/ ...

Send the function with parameters, but do not pass its output

Within my component, there is a need property that holds a static function. This function is executed by middleware to handle asynchronous API calls before rendering the component. Here's an example: static need = [ myFunc(token) ] The issue arise ...

The 'authorization' property is not available on the 'Request' object

Here is a code snippet to consider: setContext(async (req, { headers }) => { const token = await getToken(config.resources.gatewayApi.scopes) const completeHeader = { headers: { ...headers, authorization: token ...

Top method for saving information on page for Ajax calls

On my dynamically generated page, there is an array of data produced by php that I want to utilize for an ajax request. However, I am unsure of the best method to store this data on the page as it is not sensitive and does not involve a form. Currently, I ...

Problem with IE off-canvas scrolling

Currently, I am facing an issue with the scrolling functionality of an off-canvas sidebar on my Joomla 3 website. It seems to be working fine in Chrome and Firefox, but when it comes to Internet Explorer, the visible scroll bar refuses to move when attempt ...

Tips for enhancing a search algorithm

I am currently working on implementing 4 dropdown multi-select filters in a row. My goal is to render these filters and update a new array with every selected option. Additionally, I need to toggle the 'selected' property in the current array of ...

transfer an image file to a php script using ajax

Having just started, my goal is to upload an image and send it to a server for insertion into a database. Initially, all I want to do is echo the file name that I will be sending. However, I am encountering issues with this process, as I keep receiving noi ...

NodeJS npm module installed globally is unable to run the main/bin JavaScript file using node command

Here is an example of my package.json: { "name": "example-module", "version": "1.0.0", "bin": "./bin/example-module.js", "main": "./bin/example-module.js", "description": "Example module description", "homepage": "http://my.home.page.com", " ...

Error: Attempting to access property 'original_title' on an undefined object

Visitors to my website have the option to search for a specific movie title. A dropdown list will then display all matching titles, allowing users to click on a title to add that movie to their watchlist. Upon clicking a title, the function addMovie is tr ...

Determine the status of a script in PHP by incorporating AJAX

I am having trouble with my file upload page in the application. I want to display "Uploading" while the file is uploading and then show "Processing" while the file is being processed. Eventually, after the script completes, my page should redirect to a sp ...

Issue with Magnific Popup lightbox functionality, and mfp-hide is ineffective

Hello everyone, I am new to stackoverflow so please bear with me as I navigate through it. Although I am still a beginner in HTML, CSS, and JS, I have been using them for work on occasion. Recently, I implemented Magnific Popup on a website I am working o ...

Seamless mathematical computations while navigating through Javascript

I have created a basic JavaScript calculator that works efficiently. However, after obtaining the result by pressing the "=" button, I would like the returned result to be saved for future use. The "=" button should be capable of being clicked again to ret ...

How do I activate the <li> tag using jQuery?

I am currently implementing pagination on my webpage using the following JavaScript code: var pagingList = $('<ul>', {class: 'pagination list-unstyled list-inline'}); ...

The animation feature in Angular JS seems to be malfunctioning

Currently in the process of creating a slideshow using AngularJS, similar to the one found at this link, which includes navigation arrows (next and prev). Here is the HTML code snippet: <div class="carousel"> <div class="left"><input ty ...

Issues with Express js routing functionality and executing mysql queries

As I dive into learning Node and Express, I'm encountering issues with routing in Express. I aim to create a well-organized and modular code for handling routes, particularly when querying data from a MySQL database: Let's start with my app.js f ...