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
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With