Reputation: 2649
I want to add a constraint when a user rates a business. User should not be able to vote 3 because it is the default rate given by the system to any new added business to our database.
I am using AngularJS as a front-end Javascript library and to create the rating bar, I am using ui.bootstrap.rating module.
What I want to do is something like this (the case when user clicks on the fourth star)
What I tried is this
Html code
<uib-rating ng-model="rateNumber1" max="2"
state-on="'fullStar'" state-off="'emptyStar'"
aria-labelledby="custom-icons-1"
read-only="false">
</uib-rating>
<uib-rating ng-model="rateNumber2" max="1"
state-on="'thirdStar'" state-off="'emptyStar'"
on-hover="onHoverRatingNumber2()" on-leave="onLeaveRatingNumber2()"
aria-labelledby="custom-icons-1"
read-only="false">
</uib-rating>
<uib-rating ng-model="rateNumber3" max="2"
state-on="'fullStar'" state-off="'emptyStar'"
on-hover="onHoverRatingNumber3()" on-leave="onLeaveRatingNumber3()"
aria-labelledby="custom-icons-1"
read-only="false">
</uib-rating>
Javascript functions created in the controller for this purpose
/* rating a business */
$scope.rateNumber1 = 0;
$scope.rateNumber2 = 0;
$scope.rateNumber3 = 0;
$scope.onHoverRatingNumber3 = function () {
$scope.rateNumber1 = 2;
$scope.rateNumber2 = 1;
};
$scope.onLeaveRatingNumber3 = function () {
$scope.rateNumber1 = 0;
$scope.rateNumber2 = 0;
};
$scope.onHoverRatingNumber2 = function () {
$scope.rateNumber1 = 2;
};
$scope.onLeaveRatingNumber2 = function () {
$scope.rateNumber1 = 0;
};
CSS classes to create custom rating icons
.emptyStar {
height: 18px;
width: 18px;
background-size: 100% 100%;
background-image: url("../img/ratingStars/empty.png");
}
.fullStar {
height: 18px;
width: 18px;
background-size: 100% 100%;
background-image: url("../img/ratingStars/full.png");
}
.thirdStar {
height: 18px;
width: 18px;
background-size: 100% 100%;
background-image: url("../img/ratingStars/thirdStar.png");
}
Upvotes: 4
Views: 1745
Reputation: 56
You can use rating-states setting of ui.bootstrap.rating module.
From the doc
rating-states (Default: null) - An array of objects defining properties for all icons. In default template, stateOn & stateOff property is used to specify the icon's class.
First, you should specify your rating states in your controller
$scope.ratingStates = [
{stateOn: 'fullStar', stateOff: 'emptyStar'},
{stateOn: 'fullStar', stateOff: 'emptyStar'},
{stateOn: 'thirdStar', stateOff: 'emptyStar'},
{stateOn: 'fullStar', stateOff: 'emptyStar'},
{stateOn: 'fullStar', stateOff: 'emptyStar'}
];
Then create a function to reset the rating to zero when the third star is clicked (to prevent the user from choosing 3 as a rate)
$scope.changeRate = function(r){
if(r==3){
$scope.rate=0;
}
};
Finally group all together in your html
<uib-rating ng-change="changeRate(rate)"
ng-model="rate"
rating-states="ratingStates"
aria-labelledby="custom-icons-2">
</uib-rating>
Here is a working example.
Upvotes: 4