-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathecSlider.js
135 lines (115 loc) · 4.08 KB
/
ecSlider.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
(function () {
'use strict';
angular.module('ecSlider', []);
}());
angular.module('ecSlider').directive('ecSlider', ['$timeout',
function($timeout) {
'use strict';
function sanitize(newVal) {
return (isArray(newVal) ? newVal.map(maybeSanitize) : maybeSanitize(newVal));
}
function maybeSanitize(val) {
return (typeof val === 'string' ? parseFloat(val) : val);
}
function isArray(a) {
return angular.isArray(a);
}
function allInBetween(newVal, config) {
return newVal.map(function(val) {
return inBetween(val, config);
}).filter(function(val){
return val === false;
}).length === 0;
}
function inBetween(newVal, config) {
return (newVal >= config.min) &&
(newVal <= config.max);
}
function inRange(newVal, config) {
return (isArray(newVal) ? allInBetween(newVal, config) : inBetween(newVal, config));
}
function isDefined(val) {
return val != null;
}
function init(el, config, ctrl, scope) {
var s, confCopy;
if (config &&
isDefined(config.min) &&
isDefined(config.max) &&
isDefined(scope.ngModel)) {
confCopy = angular.copy(config);
confCopy.value = sanitize(scope.ngModel);
s = el.slider(confCopy);
s.on('slide', function(e) {
var newVal = e.value;
if (isDefined(newVal) &&
inRange(newVal, scope.config)) {
ctrl.$setViewValue(newVal);
$timeout(function() {
scope.$digest();
});
}
});
}
return s;
}
return {
require: 'ngModel',
replace: true,
restrict: 'E',
scope: {
config: '=',
ngModel: '=',
ngDisabled: '='
},
link: function(scope, el, attrs, ctrl) {
var slider,
render = function render(el, config, ctrl) {
$timeout(function() {
slider = init(el, config, ctrl, scope);
});
};
scope.ecSlider = {
get: function() { // visible for testing
return slider;
},
getCtrl: function() {
return ctrl;
}
};
scope.$watch('config', function() {
var newConfig = scope.config;
if (newConfig) {
render(el, newConfig, ctrl);
}
}, true);
scope.$watch('ngModel', function() {
var newVal = sanitize(scope.ngModel);
if (slider &&
isDefined(newVal) &&
inRange(newVal, scope.config)) {
slider.slider('setValue', newVal, false); // no event
}
}, true);
if (attrs.ngChange) {
ctrl.$viewChangeListeners.push(function() {
$timeout(function() {
scope.$parent.$apply(attrs.ngChange);
});
});
}
scope.$watch('ngDisabled', function() {
var newVal = scope.ngDisabled;
if (slider && newVal != null) {
slider.slider((newVal ? 'disable': 'enable'));
}
});
scope.$on('$destroy', function() {
if (slider) {
slider.slider('destroy');
}
});
}
};
}
]);