"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

When the text exceeds the designated block, it will be fragmented

I have always struggled with text elements not breaking when they exceed the boundaries of their parent element. I understand that setting a max-width of 100px will solve the issue, but it's not an ideal solution for me. I want the text to break only ...

Display images in Django using the src attribute pulled from a Python list

I am currently working on displaying a collection of images on my website. I have compiled a list of sources for each image and created a loop in the HTML file to iterate through them. Here is a snippet of the HTML body: <body> <div class="co ...

Displaying CSS image slideshow images side by side

Currently I am a student studying the fundamentals of HTML and CSS. My latest project involved creating a website showcasing my work from digital arts class, complete with a simple CSS slideshow. The original intention was to have each image displayed on i ...

Utilizing CSS to Create Fixed Position Elements

How can I create a CSS Style with a fixed position property for a div? When I place this particular div inside another div containing text, the fixed-positioned div overlaps the text, causing it to be hidden. I want to align the text and image divs next ...

Steps for building an API to connect to our proprietary database using the WSO2 API manager

Currently, I am looking to share my data from my personal postgresql database by creating an API. In this case, I plan on utilizing the WSO2 API manager for the process. I am uncertain if I am proceeding in the correct manner, so any advice on the differe ...

create a gentle appearance for an element

I am looking to replicate the visual appearance of each page on this particular website: There is something about the lighting that I really admire. I have attempted to recreate the animation, but I have been unsuccessful in my attempts. Any assistance wo ...

"Exploring the interoperability between Angular's ngSanitize and ngDragDrop

Currently, I am facing compatibility issues within my Angular application when trying to incorporate both ngSanitize and ngDragDrop. The ngDragDrop plugin can be accessed at , while ngSanitize documentation is available at https://docs.angularjs.org/api/ng ...

Exploring the Dynamic Connection: AngularJS and MongoDB

As someone who is new to MEAN stack, I am currently working on creating a simple one-page application. My goal is to connect to MongoDB and retrieve values from a specific collection using a controller. During my search for an answer, I stumbled upon this ...

Replicate the action of highlighting a section of a website and copying it to the clipboard using JavaScript

I am currently in the process of transferring an outdated application to a new platform, but I'm facing difficulty understanding the changed JavaScript code. My goal is to find a parent HTML element named "output" and then select all its child elemen ...

Effortlessly transfer various documents using the Struts2 framework combined with Dropzone.js

I am currently utilizing DropZone.js for file uploads. Here is my current configuration: Dropzone.options.myAwesomeDropzone = { url: 'UploadImages', previewsContainer: ".dropzone-previews", uploadMultiple: true, parallelUploads ...

Combining object IDs with identical values to create a new array in JavaScript

i have an array of objects that are a join between the transaction, product, and user tables. I want to merge IDs with the same value so that it can display two different sets of data in one object. Here's my data let test = [ { Transac ...

Encoding a JSON representation of an HTML list where all children are displayed at each parent item

Here is the structured list that I am currently working with: function convert( name_ref ) { name_ref = name_ref + " > ol > li"; var mylist = []; $(name_ref).each(function () { if ($(this).find('> ol > li').length){ myl ...

Best practices for updating the value of a specific key within an object that contains recursion in JavaScript/TypeScript

I have a tree component that uses the following data structure type TreeNode = { id: string, parentId: string, renderer: () => React.ReactNode, expanded: boolean, children?: Array<TreeNode>, } Now, I am looking to add functionality for ...

How do I show a personalized cookie banner based on the user's location in a NextJs application?

I have a NextJs 12 application with URLs domain.com and domain.com/es. We implemented the OneTrust cookie banner in _document.ts as shown below: <Head> <Script id="one-trust" strategy="befor ...

An effective way to prevent right-clicking on iframes across all websites

I am facing an issue with disabling right click for the iframe. I've successfully disabled it for the default URL of the IFrame, but when displaying any other webpage, the right click remains usable. Below are the sample codes I have used: document.o ...

Is there a way to confirm whether or not two files are identical?

Is there a reliable method to determine if two files are identical? I've been using a solution that involves downloading the first part of each file, converting the data to base64, and then comparing them. However, I've encountered an issue wher ...

Give Jquery a quick breather

My goal is to have my program pause for 3 seconds before continuing with the rest of the code. I've been researching online, but all I can find are methods that delay specific lines of code, which is not what I need. What I would like to achieve look ...

Backgrounds filled by nested <li> elements inside another <li> element

My website features a sidebar menu with nested lists. When hovering over a list item, a sub-list appears. However, I am having an issue where the background color fills the entire sub-list instead of just the first list item. See the images below for clari ...

Make Jekyll process HTML files even without front matter by using the Knitr tool to add front matter to the HTML files

I am currently utilizing RMarkdown in combination with knitr to produce various HTML documents. After uploading these documents to GitHub, Jekyll is utilized for rendering the files onto GitHub pages. My objective is straightforward: I want the index.html ...

Tips for personalizing tooltips in Bootstrap 4

Currently, I am utilizing Bootstrap '4.0.0-alpha.6' and attempting to customize the tooltip styles. Despite adding a custom CSS class along with using Bootstrap 4, the tooltip is not responding correctly to my specified style when hovering over. ...