Rendering a Star Rating System using angularjs

后端 未结 7 1164
执笔经年
执笔经年 2020-12-08 17:54

My app is in this Fiddle I need to render a star rating system dynamically from a http service, where the current stars and maximum stars can vary with each case.

Is

7条回答
  •  星月不相逢
    2020-12-08 18:03

    Star Rating can be done either statically (read-only) or dynamically

    enter image description here

    If you want just simply to display Rating as star then try the below one

    Static Star Rating

    Working Example

    html

    
        
    {{rating.current}} out of {{rating.max}}

    script

    var starApp = angular.module('starApp', []);
    
    starApp.controller('StarCtrl', ['$scope', function ($scope) {
        $scope.ratings = [{
            current: 5,
            max: 10
        }, {
            current: 3,
            max: 5
        }];
    }]);
    
    starApp.directive('starRating', function () {
        return {
            restrict: 'A',
            template: '
      ' + '
    • ' + '\u2605' + '
    • ' + '
    ', scope: { ratingValue: '=', max: '=' }, link: function (scope, elem, attrs) { scope.stars = []; for (var i = 0; i < scope.max; i++) { scope.stars.push({ filled: i < scope.ratingValue }); } } } });

    If you want to do Star Rating dynamically try this out

    Dynamic Star Rating

    Working Demo

    Html

    
        
    {{rating.current}} out of {{rating.max}}

    script

    var starApp = angular.module('starApp', []);
    
    starApp.controller('StarCtrl', ['$scope', function ($scope) {
        $scope.rating = 0;
        $scope.ratings = [{
            current: 5,
            max: 10
        }, {
            current: 3,
            max: 5
        }];
    
        $scope.getSelectedRating = function (rating) {
            console.log(rating);
        }
    }]);
    
    starApp.directive('starRating', function () {
        return {
            restrict: 'A',
            template: '
      ' + '
    • ' + '\u2605' + '
    • ' + '
    ', scope: { ratingValue: '=', max: '=', onRatingSelected: '&' }, link: function (scope, elem, attrs) { var updateStars = function () { scope.stars = []; for (var i = 0; i < scope.max; i++) { scope.stars.push({ filled: i < scope.ratingValue }); } }; scope.toggle = function (index) { scope.ratingValue = index + 1; scope.onRatingSelected({ rating: index + 1 }); }; scope.$watch('ratingValue', function (oldVal, newVal) { if (newVal) { updateStars(); } }); } } });

    There is a wonderful tutorial here for more explanation about Angular Star Rating

提交回复
热议问题