ng-Rating

A simple directive using the jQuery Raty plugin. Source: https://github.com/wbotelhos/raty

by phoffman

HTML

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"></script>
<link rel="stylesheet" href="//cdn.jsdelivr.net/foundation/5.0.2/css/foundation.min.css">
<div ng-app="ratyapp" ng-controller="RatyCtrl" class="panel radius">
     <h1>Ng-Raty</h1>

    <div ng-raty="ratyOptions" ng-model="rating.current" mouse-over="demo.mouseOver(stars, e);" mouse-out="demo.mouseOut(stars, e);"></div>
    <ul>
        <li>Rating: {{ rating.current }}</li>
        <li>MouseOver: {{ rating.over }}</li>
        <li>MouseOut: {{ rating.out }}</li>
    </ul>
    <div>
        <input type="number" ng-model="tempValue" />
        <button ng-click="demo.setRating(tempValue); tempValue = null;">Set Rating</button>
    </div>
</div>

CSS

.panel {
    margin: 10px;
}

JavaScript

angular.module('ratyapp', ['phoffman.ngRaty'])
    .controller('RatyCtrl', ['$scope', function ($scope) {
    $scope.demo = this;
    $scope.rating = {
        current: 0,
        over: 0,
        out: 0
    };
    $scope.ratyOptions = {
        half: true,
        cancel: true,
        cancelOn: 'https://raw.github.com/wbotelhos/raty/master/lib/img/cancel-off.png',
        cancelOff: 'https://raw.github.com/wbotelhos/raty/master/lib/img/cancel-on.png',
        starHalf: 'https://raw.github.com/wbotelhos/raty/master/lib/img/star-half.png',
        starOff: 'https://raw.github.com/wbotelhos/raty/master/lib/img/star-off.png',
        starOn: 'https://raw.github.com/wbotelhos/raty/master/lib/img/star-on.png'
    };

    this.mouseOver = function (stars, e) {
        $scope.rating.over = stars || 0;
    };

    this.mouseOut = function (stars, e) {
        $scope.rating.out = stars || 0;
    };

    this.setRating = function (value) {
        if (typeof value != 'number') return;

        // Remove negatives, round to nearest .5;
        value = (Math.round(Math.abs(parseFloat(value) || 0) * 2) / 2).toFixed(1)
        $scope.rating.current = value > 5 ? 5 : value;
    };
}]);

angular.module('phoffman.ngRaty', [])
    .directive('ngRaty', function () {
    return {
        restrict: "A",
        scope: {
            ngRaty: '=',
            ngModel: '=',
            mouseOver: '&',
            mouseOut: '&'
        },
        link: function ($scope, $element, $attrs) {
            var rating = $scope.ngModel;
            var raty = {
                score: parseFloat(rating, 10),
                click: function (stars, evt) {
                    evt.stopPropagation();
                    if (!stars) stars = 0;
                    if (!$scope.$$phase) {
                        $scope.$apply(function () {
                            $scope.ngModel = parseFloat(stars);
                        });
                    } else {
                        $scope.ngModel =...