Skip to content

Instantly share code, notes, and snippets.

@jackdempsey
Last active August 29, 2015 13:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jackdempsey/9647472 to your computer and use it in GitHub Desktop.
Save jackdempsey/9647472 to your computer and use it in GitHub Desktop.
angular.module("FundooDirectiveTutorial", []).controller("FundooCtrl", ($scope, $window) ->
$scope.rating = 5
$scope.saveRatingToServer = (rating) -> $window.alert "Rating selected - " + rating
).directive "fundooRating", ->
restrict: "A"
template: "<ul class=\"rating\">" + "<li ng-repeat=\"star in stars\" ng-class=\"star\" ng-click=\"toggle($index)\">" + "★" + "</li>" + "</ul>"
scope:
ratingValue: "="
max: "="
readonly: "@"
onRatingSelected: "&"
link: (scope, elem, attrs) ->
updateStars = ->
scope.stars = []
i = 0
while i < scope.max
scope.stars.push filled: i < scope.ratingValue
i++
scope.toggle = (index) ->
return if scope.readonly and scope.readonly is "true"
scope.ratingValue = index + 1
scope.onRatingSelected rating: index + 1
scope.$watch "ratingValue", (oldVal, newVal) ->
updateStars() if newVal
angular.module('FundooDirectiveTutorial', [])
.controller('FundooCtrl', function($scope, $window) {
$scope.rating = 5;
$scope.saveRatingToServer = function(rating) {
$window.alert('Rating selected - ' + rating);
};
})
.directive('fundooRating', function () {
return {
restrict: 'A',
template: '<ul class="rating">' +
'<li ng-repeat="star in stars" ng-class="star" ng-click="toggle($index)">' +
'\u2605' +
'</li>' +
'</ul>',
scope: {
ratingValue: '=',
max: '=',
readonly: '@',
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) {
if (scope.readonly && scope.readonly === 'true') {
return;
}
scope.ratingValue = index + 1;
scope.onRatingSelected({rating: index + 1});
};
scope.$watch('ratingValue', function(oldVal, newVal) {
if (newVal) {
updateStars();
}
});
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment