forked from IgorMinar/foodme
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fmRating.js
77 lines (61 loc) · 1.94 KB
/
fmRating.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
'use strict';
foodMeApp.directive('fmRating', function() {
return {
restrict: 'E',
scope: {
symbol: '@',
max: '@',
readonly: '@'
},
require: 'ngModel',
link: function(scope, element, attrs, ngModel) {
// Move scope to parent for isloate scope ngModels
ngModel.$setScope(scope.$parent);
attrs.max = scope.max = parseInt(scope.max || 5, 10);
if (!attrs.symbol) {
attrs.symbol = scope.symbol = '\u2605';
}
var styles = [];
scope.styles = styles;
for(var i = 0; i < scope.max; i ++) {
styles.push({ 'fm-selected': false, 'fm-hover': false });
}
scope.enter = function(index) {
if (scope.readonly) return;
angular.forEach(styles, function(style, i) {
style['fm-hover'] = i <= index;
});
};
scope.leave = function(index) {
if (scope.readonly) return;
angular.forEach(styles, function(style, i) {
style['fm-hover'] = false;
});
};
// view -> model
scope.select = function(index) {
if (scope.readonly) return;
ngModel.$setViewValue((index == null) ? null : index + 1);
udpateSelectedStyles(index);
};
// model -> view
ngModel.$render = function() {
udpateSelectedStyles(ngModel.$viewValue - 1);
};
function udpateSelectedStyles(index) {
if (index == null) index = -1;
angular.forEach(styles, function(style, i) {
style['fm-selected'] = i <= index;
});
}
},
template:
'<ul class="fm-rating" ng-class="{\'fm-rating-pointer\':!readonly}">' +
'<li ng-repeat="style in styles" ng-class="style" ' +
'ng-click="select($index)" ng-mouseenter="enter($index)" ng-mouseleave="leave($index)">' +
'{{symbol}}' +
'</li>' +
'</ul>' +
'<a ng-hide="readonly" ng-click="select(null)">clear</a>'
};
});