"Including Span icons, glyphs, or graphs within a table cell in AngularJS based on a specified condition or numerical

I'm attempting to incorporate span icons/glyph-icons using Angular within a td before displaying the country. I've utilized the code below to achieve this, but I'm looking for a more dynamic and elegant solution. Your assistance is greatly appreciated.

https://i.stack.imgur.com/R7l2D.png

    $scope.countries = [
        {name: 'Australia', rating: 0, other: "lorem ipsum"},
        {name: 'India', rating: 1, other: "lorem ipsum"},
        {name: 'Canada', rating: 3, other: "lorem ipsum"},
        {name: 'Mexico', rating: 2, other: "lorem ipsum"},
        {name: 'UK', rating: 4, other: "lorem ipsum"},
        {name: 'Germany',rating: 2, other: "lorem ipsum"},
        {name: 'USA',rating: 1, other: "lorem ipsum"}
    ];

<tr ng-repeat="country in countries">
    <td>
        <span ng-if="country.rating == 1">
                <span class="glyphicon glyphicon-star"></span>
         </span>
        <span ng-if="country.rating == 2">
                <span class="glyphicon glyphicon-star"></span>
                <span class="glyphicon glyphicon-star"></span>
         </span>
        <span ng-if="country.rating == 3">
            <span class="glyphicon glyphicon-star"></span>
            <span class="glyphicon glyphicon-star"></span>
            <span class="glyphicon glyphicon-star"></span>
      </span>
        <span ng-if="country.rating == 4">
        <span class="glyphicon glyphicon-star"></span>
            <span class="glyphicon glyphicon-star"></span>
            <span class="glyphicon glyphicon-star"></span>
            <span class="glyphicon glyphicon-star"></span>
            <span class="glyphicon glyphicon-star"></span>
      </span>
        <span>
            {{ country.name}}
        </span>
    </td>
    <td>{{country.other}}</td>
</tr>

Answer №1

Develop a custom function that generates an array of star numbers and apply it in the ng-repeat directive

$scope.generateStarArray = function(number) {
   return new Array(number);   
};


<tr ng-repeat="item in items">
   <td>
      <span ng-repeat="star in generateStarArray(item.rating) track by $index">
          <span class="glyphicon glyphicon-star"></span>
      </span>
      <span>
          {{item.name}}
      </span>
   </td>
</tr>

Answer №2

After reviewing the solution suggested by @koga, an alternative approach to achieve the same result omits the use of track by:

$scope.generateNumberArray = function(num) {
    var array = [];
    for (var x = null; x < num; x++) {
        array.push(x);
    };
   return array;   
};

<tr ng-repeat="nation in countries">
   <td>
      <span ng-repeat="star in generateNumberArray(nation.rating)">
          <span class="glyphicon glyphicon-star"></span>
      </span>
      <span>
          {{nation.name}}
      </span>
   </td>
</tr>

Answer №3

To implement this, consider incorporating a secondary ng-repeat:

<span ng-repeat="index in place.score track by $id" class="icon icon-star"</span>

Answer №4

If you're looking for a simpler approach, consider creating CSS styles to generate star ratings like this:

.star {
    color: orange;
}
.star1:before {
    content : '★'
}
.star2:before {
    content : '★★'
}

Then, you can use the ng-class function to dynamically set the appropriate star rating based on the data:

<tr ng-repeat="country in countries">
    <td>
        <span ng-class="stars(country.rating)"></span>
        <span>
            {{ country.name}}
        </span>
    </td> 
    <td>{{country.other}}</td>
</tr>
</table>
$scope.stars = function(rating) {
   return 'star star'+rating;
}

Check out a live demo here -> http://plnkr.co/edit/h3JsormYIZ6th3Kvblh5?p=preview

https://i.stack.imgur.com/XqsLU.png

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

Preventing runtime error in Next.js API routes by handling axios exceptions

I am currently working on creating an API route in Next.js that sends a request to my backend and saves the token in the cookies. However, I am facing an issue where 4xx responses are causing an Unhandled runtime error. Despite everything working correctly ...

Having trouble with getting data from Google API using jquery .get in IE9?

Having trouble understanding why this code works perfectly in Firefox but not in IE9. The script is designed to retrieve values such as street, postcode, and town from a form upon clicking a button. It then constructs a string, sends it to Google, retriev ...

Setting up a service in angularjs that is reliant on another service

One thing I'm trying to figure out is how to utilize a service like $http outside of the $get function. Is this even possible? Currently, my code loads a json file that contains a dictionary used by my application in various ways. I want users to have ...

The information in the table is spilling out beyond the boundaries

I'm facing an issue with my bootstrap table where if a field value is too long, the table extends past the container length. I tried using responsive-table to prevent this, but then a scroll bar appears at the bottom, making it difficult to view the d ...

Is there a way in Angular's ui-router to retrieve a comprehensive list of all the states that have been registered?

I'm currently developing a complex Angular application using ui-router. My goal is to implement whitelisted states, which means allowing access to certain states without requiring authentication. I want to be able to specify whole states and their sub ...

Angular is unable to fetch the chosen option from a dropdown selection

Recently, I encountered an issue with a module form that appears as a pop-up. Within this form, users can input data required to create a new object of a specific class. One field allows users to select a ventilation zone for the new room object being crea ...

Using C# within a JavaScript Element on a CSHTML webpage

Is there a way to integrate C# code into a JavaScript statement? Below is an example of the code I am trying to use: document.getElementById('part1').innerHTML = '' + '@Html.Partial("SelectCustomer.Views")' ' Views&apos ...

Minify Magic Dreamweaver Plugin

Does anyone know of a plugin that can minify javascript or css files as they are uploaded using Dreamweaver or similar coding software? For example, if I create a file like functions-global.js, the plugin would upload the original file and also generate a ...

What is the best way to manage multiple form submissions on a single page using Ajax and PHP?

I am currently working on creating an admin panel with two forms on the same page, both being handled using Ajax and PHP. Although I have written the necessary code, I am facing an issue where the data is not getting saved in the database. Data_entry.php ...

Utilize AngularJS directives within an Angular component for enhanced functionality

I'm currently in the process of enhancing an angularjs directive to integrate it into my angular component. I have successfully set up the hybrid (ng1 + ng2) environment and have also managed to inject angularjs services into Angular and utilize them ...

Utilize JavaScript when sharing on social media to avoid the possibility of embedding the entire

This javascript code snippet is extracted from www.twitter.com (simply click to view the source code). I have reformatted it for better readability: if (window.top !== window.self) { document.write = ""; window.top.location = window.self.location; s ...

Guide to implementing input fields in a form in React.js when the user chooses the "Other" option from a dropdown menu

For my project, I have implemented a multi-select dropdown input feature that saves all selected items in a useState array when the user clicks on the add icon. However, I am facing an issue where I need to render an input field only when the "Other" optio ...

What could be the reason for Sequelize to completely replace the record when updating in a put request?

I've been attempting to implement an "edit" feature within my project, but I've hit a roadblock in the process. Here's a snippet of the put request code: export const updateEvent = (event, id) => (dispatch, getState) => { request ...

React with Typescript - Type discrepancies found in Third Party Library

Recently, I encountered a scenario where I had a third-party library exporting a React Component in a certain way: // Code from the third party library that I cannot alter export default class MyIcon extends React.Component { ... }; MyIcon.propTypes = { ...

Utilizing Vue.js to dynamically update input fields based on other field values

I'm a beginner with Vue.js and Vuetify.js, and I am encountering some difficulties with the following: <v-select v-model="car.type" :items="types" label="Type" ></v-select> <div v-if="car.type === 'fiat'"> < ...

Issue with CSS not appearing in Google Chrome's coverage tab

As I delve into analyzing the extent of unused CSS on my webpage, I encounter a challenge. The webpage is crafted in Angular 7, with CSS incorporated through the angular.json build configuration. The css appears to be added to the head of the html file, e ...

What is the best way to keep the heights of two divs in sync?

Is there a way to make two divs have the same height, even though their content determines their individual heights? I am looking for a solution that doesn't involve using a table or a parent div. I'm new to JavaScript, so I'm hoping there i ...

Utilizing a Static Image Path Prop in React JS: A Step-by-Step Guide

My Main Component import React from "react"; import TopModal from "./components/topModal"; // Passing productImage to the Child Component import productImage from "../../../../../../assets/images/juices.jpg"; import { makeS ...

Unable to generate STYLE element within iframe header

Check out this jsfiddle link: http://jsfiddle.net/uTy5j/7/embedded/result/ I've encountered an issue with CodeMirror where it seems to erase the style tag I create using the following code: var preview = document.getElementById('preview') ...

How to retrieve the same value from multiple selections using Vanilla JavaScript and multiple select options?

Why do we consistently receive the same value and index when using the ctl key to select multiple options? document.querySelector('select').addEventListener('change', function(e) { console.log(this.selectedIndex) console.log(e.ta ...