angularjs实现星星评分
自定义指令
app.directive('myStars', function () {
return {
require : '?ngModel', // ?ngModel
restrict : 'E',
replace : true,
templateUrl : 'ui/templateUrl/myStars.html',
scope: {ngModel : '='},
link: function ($scope, element, attrs, ngModel) {
$scope.myStars = [1,2,3,4,5];
$scope.clickCnt = 1;
$scope.$watch('ngModel', function(newValue) {
var dataList = newValue;
console.log(dataList);
if(!dataList) return;
$scope.myStar = dataList;
$scope.clickCnt = dataList;
})
$scope.stars = function (myStar) {
$scope.clickCnt = myStar;
ngModel.$setViewValue(myStar);
} $scope.mouseoverStar = function (myStar) {
$scope.hoverCnt = myStar;
}
$scope.mouseleaveStar = function (myStar) {
$scope.hoverCnt = 1;
}
}
}
});
里面的myStars.html
<div>
<meta charset="utf-8">
<ul class="my-stars-list">
<li class="my-stars-items" ng-mouseover="mouseoverStar(myStar)" ng-mouseleave="mouseleaveStar(maStar)" ng-click="stars(myStar)" ng-class="{myStarsSel: clickCnt > $index , myStarHover: hoverCnt > $index }" ng-repeat="myStar in myStars track by $index" title="{{ myStar }}星">{{ myStar }}</li>
</ul>
</div>
html中的使用如下:
<my-stars ng-model="drLevel"></my-stars>
css样式:
.my-stars-list{
height: 34px;
line-height: 34px;
display: -webkit-box;
display: -webkit-flex;
display: flex;
}
.my-stars-items{
cursor:pointer;
font-size:;
width: 34px;
line-height: 34px;
height:34px;
background-image: url(../images/star-off-big.png);
background-repeat: no-repeat;
background-position: center center;
}
.myStarHover.my-stars-items{
background-image: url(../images/star-on-big.png);
background-repeat: no-repeat;
background-position: center center;
}
.myStarsSel.my-stars-items{
background-image: url(../images/star-on-big.png);
background-repeat: no-repeat;
background-position: center center;
}
css中的图片:
完成的效果:
获取点击的是多少直接
var level = $scope.drLevel;