Implementing Rating stars in AngularJS

Posted By : Abhinav Anand | 15-Nov-2014

Hi,

I often noticed that many web applications uses interactive stars for rating.Its a very useful tool to make your app more attractive.Implementing this without a proper code can be painful and unpleasant.

Here I am going to explain how to create rating feature using angular js directive concept and send the rating value to backend  in very simple way.This tool cantains three steps. These steps are as follows

1> Html for view


 

Rating

 
 

2 > Directive and Controller in angularjs

angular.module('StarOfMonth', [])
  .controller('OodlesRatingCtrl', function($scope) {
    $scope.rating = 5;
    $scope.rateFunction = function(rating) {
      alert('You selected - ' + rating+' stars');
    };
  })
  .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(); } } ); } }; } );

3 > 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;
}
 

Using this 'filled' class in css we are changing the colour of the stars.

You can view Demo at  Here.

These three steps can make your angular application more attractive and useful.

Keep visiting for latest blogs.

Thanks 

Abhinav Anand

About Author

Author Image
Abhinav Anand

Abhinav is a bright web developer with expertise in groovy and grails frameworks. His hobbies are listening music and playing cricket.

Request for Proposal

Name is required

Comment is required

Sending message..