JSFiddle - React, Tailwind, and code Playground
HTML
<div ng-app="FundooDirectiveTutorial" ng-init="rating = 5">
Rating is {{rating}} <br/>
<div fundoo-rating rating-value="rating" max="10"></div>
<button ng-click="rating = 7">Change rating to 7</button>
</div>
CSS
.rating{
color: #a9a9a9;
margin: 0;
padding: 0;
}
ul.rating {
display: inline-block;
}
.rating li {
list-style-type: none;
display: inline-block;
padding: 1px;
text-align: center;
font-weight: bold;
cursor: pointer;
}
.rating .filled {
color: #21568b;
}
JavaScript
'use strict';
/* Controllers */
angular.module('FundooDirectiveTutorial', [])
.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: '='
},
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.$watch('ratingValue', function(oldVal, newVal) {
if (newVal) {
updateStars();
}
});
}
}
});