Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 792
User_3535 Avatar asked Nov 04 '16 12:11

User_3535


2 Answers

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="[email protected]" 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.

like image 50
Aruna Avatar answered Nov 14 '22 22:11

Aruna


geNumber() will create an empty array with the size of the rating. ng-repeat will iterate over it no matter what is inside

track by $index is necessary in this case because you will display multiple times the same value and duplicates in a repeater are not allowed

var app = angular.module('myApp', []);

app.controller('myController', function($scope) {
  $scope.pro = [{
    product: "chicken",
    rating: 3
  }, {
    product: "fish",
    rating: 3
  }, {
    product: "pizza",
    rating: 4
  }];
  
  $scope.getNumber = function(num){
    return new Array(num);
  }  
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<body ng-app="myApp" ng-controller="myController">

  <div ng-repeat="item in pro">
    <div ng-repeat="n in getNumber(item.rating) track by $index">
      {{item.product}}
    </div>
  </div>

</body>
like image 20
Weedoze Avatar answered Nov 14 '22 23:11

Weedoze