Renaming properties in an AngularJS model

After receiving the data in a structured format, my task is to present it on a graph using radio buttons. Each radio button should display the corresponding category name, but I actually need each button to show a custom label instead of the original category name from the data. For instance, if the category name is false, the radio button should display "Other", and if it's true, then it should display "Our Company".

0: Object
    categoryName: false
    categories: Array[4]
        0: Object
        1: Object
        2: Object
        3: Object
1: Object
    categoryName: true
    categories: Array[2]
        0: Object
        1: Object

<span ng-repeat="testCat in testCategories">
<input type="radio" name="programSelector2" ng-model="testCategoryId" ng-click="load( testCat.id )" value="{{testCat.id}}" >{{testCat.name}}
</span>

I require assistance with implementing controller logic that will update the model according to the categoryName provided.

Answer №1

You have three paths you can take:

  • develop a function to determine the value
  • construct an array to figure out the value
  • utilize a condition within the expression

Using resolvement function:

$scope.resolve = function(key) {
    if (key == 'firstValue') {
        return 'First description';
    } else if (key == 'secondValue') {
        return 'Second description;
    }
}

and in the HTML

{{resolve(testCat.categoryName)}}  

With array

$scope.resolve = [];
$scope.resolve['firstValue'] = 'First description;
$scope.resolve['secondValue'] = 'Second description;

and in the HTML

{{resolve[testCat.categoryName]}}  

Utilizing conditional expression

In case categoryName only contains true or false values

 {{ testCat.categoryName ? 'First description' : 'Second description' }}

Answer №2

To implement this functionality, start by setting up a new function in the controller:

scope.getCategoryName = function(categoryName) {
   if (categoryName === true)
     return 'Other';
   else 
   {
     // your code here
   }
}

Next, you can call this function from your HTML code like so:

<input type="radio" name="programSelector2" ng-model="testCategoryId" ng-click="load(testCat.id)" value="{{testCat.id}}" >{{getCategoryName(testCat.name)}}

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 route param is throwing a "Cannot read property 'name' of undefined" error, indicating that the property

Currently, I am enrolled in an ExpressJS course on TUTS+ From the video tutorial, I have implemented the following code snippet (excerpt from video): var express = require('express'), app = express(); app.get('/name/:name', funct ...

Troubleshooting JavaScript Oscilloscope: resolving audio playback problems

I am exploring JavaScript for the first time and came across an interesting oscilloscope example on this GitHub page. It seemed quite easy to follow initially, but I am facing an issue with audio playback. Although the HTML5 audio element loads the audio f ...

I am looking to obtain a value through a JavaScript function that sums values upon clicking. The result is satisfactory, but I am seeking a way to limit the value

I only need 2 decimal values, not large ones. Can someone please help me achieve this? <script> $(function() { $("#isum, #num1, #num2, #num3, #rec1, #rec2, #rec3, #difnum1, #difnum2, #difnum3").on("keydown ke ...

Guide to fetching and displaying a complex array API using JavaScript's fetch method

Recently, I've been delving into the world of APIs and making sure I call them correctly. Using the fetch method has been my go-to so far, and here's a snippet of the code where I reference an API: fetch('https://datausa.io/api/data?d ...

In what way does s% access the title attribute within the Helmet component?

I am seeking clarification on how the reference to %s is connected to the title attribute of the <SEO /> component within the <Helmet /> component in the gatsby starter theme. Can you explain this? Link to GitHub repo On Line 19 of the code: ...

When an input element is being controlled from outside the modal using a portal, it is losing focus after a key press

[Resolved] The input component is experiencing a focus issue when any key is pressed, only when its value is controlled from outside of the portal. NOTE: I apologize for any confusion. While writing this post, I identified the problem in my code, but dec ...

I need the language chosen using Lingui's Language Switcher (i18n) to persist throughout the app, even after a refresh

I have been experimenting with Lingui for internationalization (i18n) in my app. I followed the documentation and tutorial to create a language switcher, but I am unsure how to set it up so that the selected language persists throughout the app even after ...

Error: The function Undefined is not recognized by express.io

Struggling to configure express.io with individual files for each route? Check out the examples provided. Currently, I have a typical Express setup that I want to transition to express.io: Project app.js routes servepage.js Views ...

The Vue3 property 'x' is not recognized on type 'Function' as a global property

I have encountered a strange issue with my Quasar app. I am attempting to define a global variable that consists of metadata about the application in an object format. Despite successfully compiling the app and displaying the correct information on the HTM ...

Differentiating elements from two array objects in typescript: a guide

I am facing an issue in extracting the different elements from two array objects. Here is my example: array1 = [{id: 1, a: "a", b: "b"}, {id: 2, c: "c", d: "d"}, {id: 3, e: "e", f: "f"}]; array2 = ...

Ways to modify the text of an HTML element when hovering over it

One of my elements contains the text &times; within a <span>. Is there a way to change this symbol to something else, like &infin;, when hovered over? <span class="change-text">&times;</span> When the mouse hovers over it, I ...

Using JavaScript to listen for events on all dynamically created li elements

Recently, I've created a simple script that dynamically adds "li" elements to a "ul" and assigns them a specific class. However, I now want to modify the class of an "li" item when a click event occurs. Here's the HTML structure: <form class ...

Creating a background with image overlays in React: A step-by-step guide

My challenge is to have an image that covers the entire background but it seems to stop abruptly where another object is placed, unable to extend further. I am utilizing Material UI and here is a snippet of my code: import { Image } from "../images&q ...

jqGrid - Error when the length of colNames and colModel do not match!

Whenever I implement the code below, it triggers an error saying "Length of colNames and <> colModel!" However, if isUserGlobal is false, no errors occur. The version of jqGrid being used is 4.5.4 receivedColModel.push({name:'NAME', index:' ...

Make sure to verify if all values are contained within an array by utilizing JavaScript or TypeScript

These are the two arrays I'm working with. My goal is to ensure that every value in ValuesToBeCheckArr is present in ActualArr. If any values are missing from ActualArr, the function should return 0 or false. Additionally, there is an operator variabl ...

What causes my Excel file to become corrupted when inputting new data?

My intention with this code is to insert "ABC" into cell B3 of an existing Excel document. However, when the file is written, its size decreases significantly and Excel is unable to open it. const excel = require("exceljs"); const template = "./myexcel.xl ...

Can anyone recommend a speedy sorting algorithm for an extensive list of objects in JavaScript?

Struggling to organize a large array of 2000 elements in ReactJS using JavaScript. The array includes: data = [ { index: 0, id: "404449", product_name: "ette", brand_name: "Dyrberg/Kern", base_pri ...

Retrieve a PHP file utilizing Javascript or JQuery

Is there a more straightforward method than using ajax to retrieve the contents of an HTML or PHP file and place it within a div on the current page? I am familiar with the process through ajax, but I am curious if there is a simpler alternative that doe ...

Load upcoming and previous slides in advance

Currently, I have implemented a basic slideshow on my website. It functions properly, but I am interested in preloading the previous and next slides to enhance its speed. Is there anyone who can assist me with this request? ...

The Socket.io client establishes connections with multiple servers simultaneously

Imagine this scenario: I am using nodejs and socket.io, and a question comes to mind. What would happen if one client establishes connections with multiple servers like this: socket = io.connect('http://server1') //600k sockets already connecte ...