星期六加班,教育後台也要有星級評等等級的需求,醉了……基本知道些怎麼做,網上也隨便找了找,沒什麼合意的,畢竟需求不同,也不能完全一樣不是。學習之,改之╮(╯▽╰)╭
Directive
angular.module('XXX').directive('stars', stars); function stars() { var directive = { restrict: 'AE', template: '<ul class="rating" ng-mouseleave="leave()">' + '<li ng-repeat="star in stars" ng-class="star" ng-click="click($index + 1)" ng-mouseover="over($index + 1)">' + '<i class="glyphicon glyphicon-star stars"></i>' + '</li>' + '</ul>', scope: { ratingValue: '=', hoverValue: '=', max: '=', onHover: '=', onLeave: '=' }, controller: startsController, link: function(scope, elem, attrs) { elem.css("display", "block"); elem.css("text-align", "center"); var updateStars = function() { scope.stars = []; for (var i = 0; i < scope.max; i++) { scope.stars.push({ filled: i < scope.ratingValue }); } }; updateStars(); var updateStarsHover = function() { scope.stars = []; for (var i = 0; i < scope.max; i++) { scope.stars.push({ filled: i < scope.hoverValue }); } }; updateStarsHover(); scope.$watch('ratingValue', function(oldVal, newVal) { if (newVal) { updateStars(); } }); scope.$watch('hoverValue', function(oldVal, newVal) { if (newVal) { updateStarsHover(); } }); } }; return directive; /** @ngInject */ function startsController($scope) { // var vm = this; $scope.click = function(val) { $scope.ratingValue = val; }; $scope.over = function(val) { $scope.hoverValue = val; }; $scope.leave = function() { $scope.onLeave(); } } }
CSS
.rating { color: #a9a9a9; margin: 0; padding: 0; text-align: center;}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: #f00;}.rating .stars{ font-size: 20px; margin-right: 5px;}
Controller
//星星等級評分 $scope.max = 6; $scope.ratingVal = 6; $scope.hoverVal = 6;//我這需求是預設六個星全滿(淡騰,反正也招不出神龍.因為還差一個.)一般的話,ratingVal和hoverVal都寫0就可以了。 $scope.onHover = function(val) { $scope.hoverVal = val; }; $scope.onLeave = function() { $scope.hoverVal = $scope.ratingVal; } $scope.onChange = function(val) { $scope.ratingVal = val; }
HTML
<stars rating-value="ratingVal" hover-value="hoverVal" max="max" on-hover="onHover" on-leave="onLeave"></stars>ratingVal:{{ratingVal}};<br/>hoverVal:{{hoverVal}}
說幾句, 星星那東西,可以直接IME敲出來,也可以用unicode搞出來,字型檔什麼的都行,你要硬用圖片的話……把ngClass換成ngSrc也可以試試,代碼改改也行,精靈圖改改background-position也湊合過,╮(╯▽╰)╭ 想了一下,比較累,祝你成功。
如果是那種商城網站只是要看評價等級的話,複用代碼也可以,加個readonly屬性。
directive: scope: { readonly: '@' } function startsController($scope) { // var vm = this; $scope.click = function(val) { if ($scope.readonly) { return; } $scope.ratingValue = val; }; $scope.over = function(val) { if ($scope.readonly) { return; } $scope.hoverValue = val; }; }controller: $scope.readonly = false;html: readonly={{readonly}}.
寫到這,突然意識到今後一定會改需求,加功能(已然習慣)。我還是默默地加上readonly吧……
指令這玩意,深了很繞,我也弄不熟,每次寫還得翻翻以前寫的代碼,畢竟渣渣。每次不要複用的代碼,我都懶得用指令,畢竟菜鳥。
以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援雲棲社區。