angular-rating

by Filipe Tedim

HTML

<script src="https://use.fontawesome.com/2bd9c462bc.js"></script>
<div ng-app="myApp">
    <div ng-controller="MyCtrl">
        <h3>Hello, Superhero!</h3>

        <div>Rating: {{rating.value}}</div>

        <div data-angular-rating ng-model='rating.value' max={{maxValue}} default-value=2 icon-empty="fa-star-o" icon-full="fa-star" icon-hover="fa-star" color-base="black" color-selected="orange" color-hover="orange" icon-size="50" on-change="fn()" decimal></div>
		
		<div>{{callbackText}}</div>
    </div>
</div>

CSS

.angular-rating-icons {
    text-align: left;
    display: inline-block;
    padding: 0;
    list-style: none;
}

.angular-rating-icons > li {
    display: inline-block;
    padding: 0;
    cursor: pointer;
}

.angular-rating-icons-decimal > li {
    overflow: hidden;
    position: relative;
}

.angular-rating-icons-decimal > li > i {
    position: absolute;
}

JavaScript

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

app.directive('angularRating', function() {
    return {
        replace: true,
        require: 'ngModel',
        scope: {
            ngModel: '=',
			onChangeFunction: '&onChange'
        },
        template: '' +
            '<ul ng-class="[listClass, decimal]">' +
            '<li ng-repeat="icon in icons track by $index" ' +
            'ng-style="getListItemStyle($index)" ' +
            'ng-click="setValue($index)" ' +
            'ng-mouseenter="paintIcons($index)" ' +
            'ng-mouseleave="resetIcons()" ' +
            '>' +
            '<i ng-class="getClass($index)" ng-style="getIconStyle($index)"></i>' +
            '</li>' +
            '</ul>',

        link: function(scope, element, attrs, controller) {
            // Settings
            scope.icons = new Array(+attrs.max || 5);
            scope.value = controller.$viewValue || (+attrs.defaultValue || 0);
            scope.size = +attrs.iconSize || 20;
            scope.spacing = +attrs.iconSpacing || 5;
            scope.listClass = 'angular-rating-icons';
            scope.readOnly = !(attrs.readonly === undefined);
            scope.decimal = !(attrs.decimal === undefined) ? 'angular-rating-icons-decimal' : undefined;

            // Colors
            var colorBase = attrs.colorBase || 'black';
            var colorSelected = attrs.colorSelected || 'orange';
            var colorHover = attrs.colorHover || 'orange';

            // Different states
            var iconBase = attrs.iconBase || 'fa';
            var iconEmpty = attrs.iconEmpty || 'fa-star-o';
            var iconFull = attrs.iconFull || 'fa-star';
            var iconHover = attrs.iconHover || 'fa-star';

            // Model
            controller.$render = function() {
				scope.value = controller.$viewValue === 0 ? 0 : controller.$viewValue || scope.value;
				
				// update model safeguard/fallback should it not be initialized before
				controller.$setViewValue(scope.value);
...