Displaying icon.png in Angular based on item attribute - a step-by-step guide

My data is stored in an array of objects with information about people:

[{"name":"Steve", "hourly_wage":16, "status":"part-time"},
{"name":"Maria", "hourly_wage":25, "status":"full-time"},
{"name":"Jose", "hourly_wage":21, "status":"former"}]

I am looking to visually represent each person's employment status using icons. A full circle for full time, a half circle for part time, and an empty circle for former employees. How can I achieve this using Javascript/Angular? Would using if statements inside ng-hide be the best approach?

Answer №1

In my view, the most straightforward approach would be to create a mapping and then utilize it.

JavaScript:

$scope.statusIconMapping = {"part-time": "half_circle.jpg", 
    "full-time": "full_circle.jpg", 
    "former": "empty_circle.jpg"
};

HTML Markup:

<div ng-repeat="employee in employees">
    ...
    <img src="{{statusIconMapping[employee.status]}}" />
</div>

Answer №2

How you bring in those icons will determine the method to use. Are they images? Fonts? To make it work, assuming you are using images named part-time.jpg, full-time.jpg, former.jpg and located in a /resources folder, try the code below:

<div ng-repeat="obj in list">
    <img ng-src="/resources/{{obj.status}}.jpg"/>
    {{obj.name}}
</div>

This approach is also suitable for fonts and other resources.

Answer №3

To determine the icon displayed, utilize the status property as your condition in the HTML like so:

<div ng-src="/images/icons/{{ status }}.png"></div>

...resulting in

<div src="/images/icons/part-time.png"></div>
or similar based on the status.

It is crucial to use ng-src over src to avoid issues where the page loads before AngularJS renders, causing the browser to search for a file named {{ foo }}, which does not exist.

Avoid unnecessary complexity in your logic by simply adding another property to the JSON for displaying icons based on status. For instance, if status is full-time, set 'full-circle.png' as the icon in the JSON, or use the status itself as the icon name for simplicity.

Consider this approach:

{
   status: 'full-time', icon: 'full-circle.png'
}

Alternatively:

{
   status: 'full-time'
}

Name your icon file as full-time.png for easy integration into the HTML without additional logic or properties.

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 implementing the quill-image-drop-module with Vue 3

I am currently utilizing the vueup/vue-quill package for Vue 3 and I would like to incorporate the kensnyder/quill-image-drop-module. This is the snippet of my code: Main.js import { QuillEditor } from '@vueup/vue-quill'; import '@vueup/vu ...

Add an item to the second occurrence of a specific HTML class

I am facing a challenge where I need to add an element to another element, but the target element is only identified by a class that is used multiple times. Specifically, I need to append to the last or second occurrence of the element. You can see a visua ...

Unleashing the power of React: Integrating raw HTML <a href> tags with JavaScript

I am currently working on a small web app that mimics browsing WikiPedia by fetching raw HTML content of WikiPedia articles through its API. I then display this HTML in my app using "dangerouslySetInnerHTML". I am faced with the challenge of enabling a us ...

Start by setting up the Select box to include a loading option, which will then be removed once the

I am facing an issue with a select box in my form that loads data using a JSON request in AngularJS. To handle the delay in loading the data, I added a temporary option: <option value="">Loading...</option> However, once my model is loaded, t ...

Looking for a way to upload only part of a large file using HTML and PHP

Is it possible to create a PHP script that can upload only the first 1 MB of a very large file? Can this be achieved with a standard form upload in PHP by closing off the connection after 1 MB is uploaded? I have researched various uploaders (HTML5/Java ...

Is it possible to combine the existing request parameters with a new parameter in JSP/JSTL/JQuery?

Here is a sample URL: http://127.0.0.1:8080/admin/seller?email=tim%40example.com Below is a snippet of JSP code: <a class="btn btn-primary ${page==pages||pages==0?'disabled':''}" href="?page=${page + 1}">Next</a> I am ...

Root scope digest trigger delay

When invoking $scope.$apply() ten times consecutively, it is expected that ten root scope digests will occur. If the call to $scope.$apply() is debounced so that the trailing call always completes, can we assume that the final state of the application rem ...

What is the best way to send a parameter in pug?

My template with URL parameter is not functioning properly doctype html html head block head meta(charset="utf-8") meta(name="viewport", content="width=device-width") meta(http-equiv="X-UA-Compatib ...

Struggling to remove an image while using the onmouseover event with a button?

I am encountering an issue with hiding an image using the onmouseover event not applied directly to it, but rather to a button element. The desired functionality is for the image to appear when the mouse hovers over and disappear when it moves away. Here&a ...

Is it necessary for the raycaster to be positioned within the render() function at all times?

Looking to capture the mouse double-click event's location and generate a 3D object in that spot within the scene. My understanding is that the raycaster, which is in the render() function, constantly updates the mouse location. I am interested in ha ...

Issue with error handling not being triggered when calling SAPUI5 function()

IBAN validation within a SAPUI5 Wizard is causing some issues for me. I am utilizing a functionImport on a V2 ODataModel (sap.ui.model.odata.v2.ODataModel) to perform this validation. Despite receiving a 202 status code, the request actually failed. Here ...

Managing timestamps of creation and modification with Sequelize and Postgresql

As a newcomer to Sequelize, I find myself grappling with the intricacies of model timestamps management. Despite prior experience with another ORM in a different language, I'm struggling to wrap my head around how to automatically handle "createdAt" a ...

Axios.post makes the request twice

Can anyone help me with an issue regarding axios.post where it sends the same request twice with identical data? I have searched online for a solution but haven't found anything. Any ideas on how to resolve this problem? https://i.sstatic.net/lXTss.p ...

Vue - Find matching data in an array of objects and render it on the page

I have a Vue.js data array that contains information about counties in the UK. I want to create links between related county pages based on the data in the array. To achieve this, I need to loop through the main county object and compare the items in the ...

Avoiding cheating in a JavaScript game

I am in the process of creating a JavaScript/JQuery game that resembles a classic brick breaker. The game includes features such as scoring, levels, and more. I have plans to add a leaderboard where users can submit their final scores. However, my concer ...

Having trouble with AngularJS? Ng-switch not updating after ng-click?

Initially in my code, I check if a user has the ability to flag a discussion. If they do, I use ng-switch where upon flagging, a success message is displayed: <div ng-if="canFlag(discussion)"> <div ng-switch="isFlagging" ng-click="fla ...

How can I obtain the width of one element and then use it to adjust the size of another element that is

Currently, I am working on a dropdown menu and facing an issue with setting the submenus to match the width of the top-level page. In my HTML structure (specifically for a WordPress theme), it looks something like this: <ul class="menu"> <li ...

Disable the click functionality while preserving the hover feature

Due to my previous question being incorrectly marked as a duplicate, even though it wasn't, and no one is rectifying the mistake, I am re-posting my inquiry. I am dealing with an <a> element that has a default onClick function. This <a> a ...

Update the src of #contentImg to display the image from the clicked link

I have a jQuery mobile listview set up where I want to use jQuery to change the source of #contentImg to the source of the image thumbnail that is clicked. So, when an 'a' element within a 'ul' with the data-role of "listview" is click ...

Leverage JSON data within an AngularJS controller

I have a JSON list in Angular that looks like this: vm.allnews = actualNews; After checking it with console.log, I can see that it's working fine and I am able to retrieve all news from the array list. Each news item has a title which I can display ...