Angular 5 shining star rating indicator

I'm looking to implement a 5-star rating bar using Angular, and currently my code only works for integers with full stars. However, I would like to modify it to display half stars for decimal values. How can I achieve this without using an IF statement in my Angular version?

<li ng-repeat="Star in [1,2,3,4,5]">
     <div ng-switch="Item.ItemDetails.Rating >= Star">
          <div ng-switch-when="true">
               <img src="~/Images/star.png" class="star" />
           </div>
           <div ng-switch-when="false">
               <img src="~/Images/star_gray.png" class="star" />
           </div>
     </div>
</li> 

Answer №1

I discovered a simple approach to this problem.

<li ng-repeat="Star in [1,2,3,4,5]">
                                    <div ng-switch="store.Rating >= Star">
                                        <div ng-switch-when="true">
                                            <img src="~/Images/star.png" class="star" />
                                        </div>
                                        <div ng-switch-when="false">
                                            <div ng-switch="store.Rating > (Star-1)">
                                                <div ng-switch-when="true">
                                                    <img src="~/Images/star_half.png" class="star" />
                                                </div>
                                                <div ng-switch-when="false">
                                                    <img src="~/Images/star_gray.png" class="star" />
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </li>

Answer №2

This instance showcasing the use of bootstrap could be beneficial: Plunker

HTML

<form class="Scroller-Container" ng-submit="submit()" ></form>

    <rating  
           value="rate" 
           max="max" 
           readonly="isReadonly" 
           on-hover="hoveringOver(value)" 
           on-leave="hoveringLeave(rate)" >
   </rating>
    <span 
         class="badge" 
         ng-class="{'badge-warning': percent<30, 'badge-info': percent>=30 && percent<70, 'badge-success': percent>=70}" 
         ng-show="overStar && !isReadonly">
         {{percent}}%
    </span>

<input type="submit" id="submit" value="Submit" />
</form> 

JS

var RatingDemoCtrl = function ($scope) {

    $scope.myRate = 0;

     $scope.submit = function() {
         console.log($scope.percent) ; //null
     }

     $scope.rate = 1;
     $scope.max = 5;
     $scope.isReadonly = false;
     $scope.percent = 20;

      $scope.hoveringOver = function(value,object) {
        console.log('hoveringOver', value);
        $scope.overStar = value;
        $scope.percent = (100 * $scope.overStar) / $scope.max;
      };

       $scope.hoveringLeave = function(rate) {
         console.log('hoveringLeave',  $scope.rate);

       $scope.percent = (100 * $scope.rate) / $scope.max;
      };
    };

You can modify it and incorporate a custom image. However, the methodology remains the same (using ng-class, for example)

Also, here is an icon library where you can access star/half-star/empty star icons: Awesome Icons

Answer №3

Although your question falls under the category of an AngularJs query, I have a unique suggestion to achieve the desired effect using a combination of Angular Js and a touch of Css magic.

My approach would involve utilizing two 5-star images - one 'Empty' or gray, and one 'Full' or yellow:

Next, I would create a div containing the gray stars, along with an overlay div housing the bright yellow stars. By using the background-image property instead of traditional <img> tags, I could easily adjust the width of the overlay div to reflect the desired rating level.

Feel free to test this out on this quick fiddle (please excuse the low-quality images, they were sourced quickly for demonstration purposes - experiment with adjusting the width in the full-star div to see the effect).

To begin, structure the Html as follows:

<div class="star-rating">
    <!-- The '|| 0' prevents Rating property from being undefined or null -->
    <div class="full-star" style="width: {{Item.ItemDetails.Rating * 20 || 0}}%"></div>         
    <div class="empty-star"> </div>
</div>

The width set on the full-star will determine the visibility of the star.

Accompanied by the following Css:

/* Instead of using <img> tags, utilize background-image for half-star results */
.star-rating {
    position: relative;
    /* Add any other preferred styles here */
}

.full-star {
    position: absolute;
    z-index: 1;
    height: 100%;
    background-image: url('PATH_TO ~/Images/star.png');
    /* Add any other preferred styles here */        
}

.empty-star {
    width: 100%;
    height: 100%;  
    background-image: url('PATH_TO ~/Images/star_gray.png');
    /* Add any other preferred styles here */
}

Cheers!

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

Repeated tweets detected within real-time Twitter stream

I've been working on developing a live update Twitter feature, but I've noticed that it sometimes duplicates tweets and behaves erratically. Did I make a mistake somewhere in my code? http://jsfiddle.net/JmZCE/1/ Thank you in advance (note: I p ...

Slick.js integrated with 3D flip is automatically flipping after the initial rotation

I'm encountering an issue with my CSS3 carousel and 3D flipping. Whenever I navigate through the carousel and flip to the next slide, the first slide seems to automatically flip/flop after completing the rotation. You can see a visual demonstration o ...

Display loading animation until Google Maps is fully loaded - Utilizing AngularJs

Is there a way to check the readiness of Google Maps before displaying it? I'd like to show a preloader block while the Google Maps is loading. Here is the factory code I am using: var map = false; var myLatlng = new google.maps.LatLng(48.6908333333 ...

Snapshots in AngularJS SEO with PhantomJS can be created either before or during the crawling process

What is the best approach for generating snapshots (snapshots being a plain HTML version of an Angular state/route created for SEO purposes)? Should it be done every time an author adds a post in a blog? Or should it be generated during crawling? Link t ...

Designing in Ionic 3.x: Implementing Ion-Icon with a gradient backdrop (ion-chip)

Is there a way to add a gradient background to an icon? I attempted to nest the ion-icon within an ion-chip, like so: <ion-chip class="my-chip"> <ion-icon name="basket></ion-icon> </ion-chip Then, in the .css file: ...

using JQuery, add a class on click event or on page load

Solved It! After encountering a problem created by some sloppy moves on my part, I managed to solve it. However, another issue arose: adding the class current to li with data-tab="tab-1 upon page load. $('ul.tabs li').click(function(){ ...

Loading a .css file in advance using NextJS

We have integrated NextJS and Material-UI into our website, but we are facing an issue with FOUC (Flash of Unstyled Content) upon page loading. After some investigation, I discovered that the JS files are loading faster than the CSS file, causing the probl ...

Create a stand-alone scope for reusable Angular directives

I have developed a custom directive called myContent 'use strict'; angular.module('myModule').directive('myContent', function() { return { restrict: 'E', templateUrl: 'myContent.html', cont ...

Executing a Python script within an HTML page using Django and extracting a variable from an input form

I have created a sentiment analysis Python script, but now I want to integrate it with an HTML page. The goal is to take input from the HTML form, process it using the Python script, and then display the results back on the HTML page. Currently, I am usin ...

Are HTML tables a viable fix for the problem with ng-repeat?

Let's talk about a fictional dataset that mirrors tabular data found in Excel. function SU(name: String, data: Array<any>) { this.name = name, this.data = data }; function Month(month: String, year: String, goal: Number, projection: ...

Unable to remove stock using delete query

Currently, I am working on a clothing shopping website where the admin can manage the stock by adding, updating, and deleting items. However, I have encountered an issue with my delete query. The problem lies in the fact that when I click on the delete b ...

Angular 6: Issue TS2339 - The attribute 'value' is not recognized on the 'HTMLElement' type

I have a textarea on my website that allows users to submit comments. I want to automatically capture the date and time when the comment is submitted, and then save it in a JSON format along with the added comment: After a comment is submitted, I would li ...

I encountered a warning while running the npm command. Can someone provide guidance on how to address this issue?

npm WARNING config key key and cert are no longer utilized for most registry functions. npm WARNING config Use registry scoped keyfile and certfile instead. npm WARNING config Example: npm WARNING config //another-registry.tld/:keyfile=/path/to/key ...

Tracking lengthy calculations in HTML using JavaScript is a breeze with this straightforward method

Need assistance with updating HTML page during a long loop process. var updateLog = document.getElementById("log"); for (count = 2; (count < 10000 && calculatedPower < power); count = count * 2) { calculatedPower = calculate_power(count, w, df, de ...

Angular: The most efficient method for creating a customized HTML page with unique styles specifically for PDF generation

Struggling with PDF generation and the challenge of preparing hidden HTML is my current hurdle. The backend team has built a PDF generation service that requires passing an HTML string as a parameter. My task is to hide all HTML elements upon clicking the ...

What is the best way to evenly distribute items in nested CSS Grid Columns?

Check out this JSFiddle link for a simple Google.com recreation. I'm attempting to organize the top navigation bar by creating separate containers for About, Store, Gmail, and Images. The issue seems to be related to the justify-items:center; propert ...

How can we stop elements from suddenly moving around in a canvas?

Below is the pseudocode I have come up with: when the move button gets pressed: currentCirclePos = circleX; moveTimer = setInterval(move, 10); The move function implementation is as follows: var move = function() { circleX += a slight moveme ...

What is the best way to enhance the visibility of the navigation items in my Bootstrap 4 navbar?

While working with Bootstrap 4, I encountered an issue where the text navigation items in the navbar were appearing semi-transparent regardless of my efforts to adjust the code. The dark blue background color of the navbar was causing the opacity to make i ...

support for wavesurfer.js in IE10 is not compatible with angular

In the process of developing an Angular application, I am utilizing the wavesurfer.js plugin to display media in wave format. While this functionality works smoothly in Chrome, it encounters issues in IE10 and IE11. Any assistance would be greatly apprecia ...

What is the best way to utilize clip() in html canvas when using text as a path?

I have written the code below, which is close to what I am trying to achieve but doesn't quite get there. My goal is to fill text in multiple colors, currently it is only in #FF00FF. Check out the Playground I suspect the issue lies in my lack of kn ...