Angular: Assigning a key from one variable to a value in another

I am currently facing a challenge with rendering a form on a page using ng-repeat, where the data for this form is dynamically fetched from a request. Within this data, there is a nested array called "categories" which contains IDs. I want to display the names corresponding to these IDs on the form instead of the IDs themselves. Another request returns an array with names associated with these IDs. How can I map the key-value pairs from one variable to another in order to display the list of names on the page?

You can find my problem on this plunker. Any help would be greatly appreciated, thank you in advance.

Here is the HTML code of my form:

<form style="padding: 15px" ng-submit="submitForm(rowData)">
    <div class="form-group row">
        <div ng-repeat="(key, value) in rowData">
            <div  ng-if="key | id">
                <label class="col-sm-6">{{key | makeUppercase}}</label>
                <div class=" col-sm-6">
                    <input class="form-control rowValue"
                           id="rowData[key]"
                           ng-if="!isObject(value)"
                           type="text"
                           ng-model="rowData[key]"/>
                    <span class="form-control rowValue"
                         id="categories"
                         ng-if="isObject(value) && key == 'categories'"
                         ng-model="rowData.categories">   
                             {{rowData.categories}}
                    </span>
                </div>
            </div>
        </div>
    </div>
    <div class="pull-right">
       <button type="submit" class="btn btn-default" 
               ng-if="rowData">Save</button>
       <button type="button" class="btn btn-default" ng-if="rowData"
               ng-click="cancelForm()">Cancel</button>
      </div>
</form>

Answer №1

Although my approach may be considered simple, it effectively showcases the desired outcome. I have incorporated this function into your controller

  $scope.getCategoryNames = function(ids){
    var categoriesName = [];
    for (var j = 0; j < ids.length; j ++){
    id = ids[j];
   for(var i= 0; i < $scope.categories.length;i++)
   {
      if ( $scope.categories[i].id == id){
        categoriesName.push($scope.categories[i].name);
      }
   }
 }

  var str = categoriesName.join(', ');
  return str;
}

In your HTML code, implement the function as shown below

<span class="form-control rowValue"  id="categories" ng-if="isObject(value) && key == 'categories'" ng-model="rowData.categories">
                       {{getCategoryNames(rowData.categories)}}</span>

Visit plnkr link here

Answer №2

To enhance your controller, you can add a custom method that correlates the numbers found in $scope.rowData.categories with $scope.categories.id to retrieve the corresponding category names:

$scope.obtainCategoryName = function (categoriesArr) {
    return categoriesArr.map(function(curr) {
        return $scope.categories.filter(function(el){
            return el.id === curr; //extract the correct category based on its id
        })[0].name; //access the selected item and fetch its name property
    })
}

Don't forget to adjust your HTML code to incorporate this new method:

<span>
    class="form-control rowValue"
    id="categories"
    ng-if="isObject(value) && key == 'categories'"
    ng-model="rowData.categories">
     {{obtainCategoryName(rowData.categories)}}
</span>

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

What is the best approach for invoking two services using a single provider factory?

Welcome! I'm having a little trouble setting up a discussion platform where users can post and comment. I've created two REST services for this purpose, but it seems like the commenting functionality is not working as expected. Could anyone help ...

Attempting to integrate a three.js OBJLoader within an HTML canvas

My issue is quite straightforward: I attempted to connect a three.js script with an HTML canvas, but I was unsuccessful and now I'm unsure how to proceed. Here is the code I have (I've already loaded the necessary scripts in the HTML head): wi ...

Struggling to click on a link while viewing the site on your mobile device?

Recently dove into the world of implementing mobile responsive design for a website I've been working on. While conducting some testing, I observed that the main tabs which direct users to different sections of the site, normally easy to click on desk ...

Blank YouTube Popup Modal

I am in the process of creating a pop-up modal that contains an embedded YouTube video, but my modal is not displaying properly. I am utilizing Bootstrap and have two separate sections along with JavaScript code. When the modal appears, it remains empty. I ...

ng-html-bind for a label with a checkbox

Currently, I have a view that uses the standard bootstrap layout for checkboxes. In this layout, the input is located within the label tag. <div class="checkbox"> <label ng-bind-html="vm.trustedHtml"> <input type="checkbox" ng- ...

Experiencing a DNS error while running a JavaScript script using Node.js

const { Client, EmbedBuilder, GatewayIntentBits, Collection, Events, Partials } = require("discord.js"); require("dotenv").config(); const { Guilds, GuildMembers, GuildMessages } = GatewayIntentBits; const { User, Message, GuildMember, ...

The ng-controller is not functioning properly even when being correctly invoked

I tried out some simple angularjs code, utilizing nodejs, angularjs, and html. Here are my files: https://github.com/internial/test. I decided not to include the node_modules folder as it was too large. On localhost:8080, this is the result: {{1 + 64}} ...

Passing an array to web service as parameters using Swift

I've been struggling to send an array object to a web service. Whenever I attempt to add the array to parameters, it throws an error. Despite trying various methods, none have proved to be effective. The goal is to include ("assignees" : newList) in ...

Transferring an MSAL token to the backend with the help of Axios

I encountered an issue while attempting to send the user ID, which was previously decoded from a JWT token along with user input data. The problem arises when I try to send the data and receive an exception in the backend indicating that the request array ...

Scroll-triggered closing of modals in Next Js

I have integrated a Modal component into my Next.JS application, and I have implemented a functionality to close the modal when the user scrolls outside of it. However, this effect is also triggering when the user scrolls inside the modal. How can I modi ...

React state object iteration doesn't produce any visible output

Trying to dynamically showcase checkboxes with starting values from the state using Material-UI for UI components. tagState: { All: true, Pizza: false, Breakfast: false, Chicken: false } Utilized Object entries and forEach to generate checkbox ...

Retrieve values from the query string (specifically from table rows and cells) for each individual line and display them in

i have some code, see: <script> $$.ready(function() { // Profile Dialog $( "#user-dialog" ).dialog({ autoOpen: false, modal: true, width: 400, open: function(){ $(this).parent().css('overflow', 'visible') ...

Using AngularJS to manipulate the DOM after the view has completely loaded

Sorry for the lengthy explanation - I hope it doesn't deter too many readers. While my current setup is functional, I'm unsure if it's the most optimal way to go about things. Therefore, I'm seeking some guidance. I have a webpage wher ...

Invoke an RxJs observable to handle errors and retry the process

I have an observable called submit$ that submits a form. If this observable encounters an error with status code 403, it means the user is not authorized and needs to log in first. Is there a way to automatically trigger another observable when a specific ...

Is it possible to save the project by generating incremental JSON diffs?

In the process of developing a web-based paint program, I have implemented a system where the user's artwork state is saved as a json object. Each time an addition is made to the client's undo stack (which consists of json objects describing the ...

Accessing website using Facebook credentials

I'm currently in the process of integrating Facebook Login on my website and have a few questions. I've encountered a problem where, upon receiving user permission, I need to create a new account in my database in order to utilize certain functio ...

Utilize Vue: Bring in the router within a helper class and navigate to a specific

I'm new to utilizing Vue, and I am currently attempting to import my existing router instance into a JavaScript class where I manage the Authentication. This is the content of my router file: import Vue from 'vue'; import Router from &apos ...

Transforming data into a flat JSON format using jq

Currently, I am dealing with JSON data that needs to be inserted into a SQL database. This particular data is sourced from Google Cloud Firestore. Here is the input: { "0": { "filed1": "xxxx", "field": "zzzz" }, "1": { "field1": "xxx", ...

Exploring the functionality of ISO 8601 periods with JavaScript

Has anyone successfully compared ISO 8601 periods in JavaScript to determine which period has a longer duration? For example, is P6M (6 months) longer than PT10M (10 minutes)? I haven't been able to find any built-in solutions for this. Any suggestio ...

Using Object Value as Variable instead of String in JavaScript/React

When working with React & JavaScript, I am storing an input name as a string in an object: window.ObjectOne = { ObjectOneKey: "MyInputName", } The input name can be an object path like "Object.FirstName" or a variable name "MyVariableName" What I am at ...