Ramanaa Gj Ramanaa Gj - 10 days ago 5
Javascript Question

CSS Star Rating with ng-repeat and json data using angularjs

Want to show a

div
n times according to the value which was received from JSON.

My object:

$scope.pro = [
{
product: "chicken",
rating: 3
},
{
product: "fish",
rating: 3
},
{
product: "pizza",
rating: 4
}
];


If a product has 3 ratings means the
div
have to show three times, like a star rating.

How to do it in angular.js?

My Plunker Demo

Answer

Can you try this,

JS

$scope.pro = [{product: "chicken", rating: 3},{product: "fish", rating: 3},{product: "pizza", rating: 4}];

var ratingTotal = 5; 

$scope.getRepeater = function() {
   return new Array(ratingTotal);
};

Html

<!DOCTYPE html>
<html ng-app="myApp">

  <head>
    <script data-require="angular.js@1.3.15" data-semver="1.3.15" src="https://code.angularjs.org/1.3.15/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <body ng-controller="myController">

    <div ng-repeat="array in pro">{{array.product}} <span class="star-icon" ng-repeat="r in getRepeater() track by $index" ng-class="{'full': ($index + 1) <= array.rating, 'half': ($index + .5) == array.rating}" ></span></div>

  </body>

</html>

Note: The class name for selected star is mentioned as 'full' and feel free to change this.

Comments