-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathslider-directive.js
2283 lines (1991 loc) · 93.1 KB
/
slider-directive.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
@toc
@param {Object} scope (attrs that must be defined on the scope (i.e. in the controller) - they can't just be defined in the partial html). REMEMBER: use snake-case when setting these on the partial!
TODO
@param {Object} attrs REMEMBER: use snake-case when setting these on the partial! i.e. my-attr='1' NOT myAttr='1'
TODO
@usage
partial / html:
TODO
controller / js:
TODO
//end: usage
*/
'use strict';
/*
Slider directive
Creates a slider on the page.
Example Calls:
HTML:
<jrg-slider-directive slider-id = 'my-slider' slider-handle-variable = 'my_var'> </jrg-slider-directive>
<jrg-slider-directive slider-id = 'my-slider' slider-handle-variable = 'my_var' slider-opts = 'opts'> </jrg-slider-directive>
JAVASCRIPT:
This is an example of a full slider-opts object, with every field defined and set to its default value. You can and should remove unneeded keys.
This object would be defined in the controller of the html creating the slider.
I recommend copying and pasting this object into your controller. Then you can change its name, adjust values, and delete keys you don't need.
$scope.opts =
{
'num_handles': 1,
'slider_min': 0,
'slider_max': 100,
'precision': 0,
'scale_string': '[1, 1]',
'zero_method': 'newton',
'increment': 0,
'user_values': '',
'evt_mouseup': '',
'slider_moveable': true,
'use_array': true,
'rotate': 0,
'bar_container_class': 'jrg-slider-directive-bar',
'left_bg_class': 'jrg-slider-directive-bar-active',
'interior_bg_class': 'jrg-slider-directive-bar-active',
'right_bg_class': 'jrg-slider-directive-bar-inactive',
'handle_class': 'jrg-slider-directive-bar-handle',
'handle_html': '<div class = "jrg-slider-directive-bar-handle-inner"></div>',
'units_pre': '',
'units_post': '',
'use_ticks': false,
'ticks_values': [0, 100],
'ticks_class': 'jrg-slider-directive-ticks',
'ticks_values_container_class': 'jrg-slider-directive-ticks-values-container',
'ticks_value_class': 'jrg-slider-directive-ticks-value',
};
****************************************************************************
READING VALUES
Option 1: Variable
Use the variable you specified for slider-handle-variable
Option 2: Event
To read a value from the slider with an event, you must know the slider_id. This is necessary since there may be multiple sliders in the same parent element.
To read a value from a single handle, you must know the handle's index. If you do not give an index, you will receive the first (leftmost) handle's value.
Handles are zero-indexed, and arranged in increasing order from left to right.
The following sample code would get the value of the 3rd handle from the left (index 2).
var evtReadSliderValue = 'evtSliderGetValue' + slider_id;
$scope.$broadcast(evtReadSliderValue, {'handle' : 2}); //tell directive to report the third handle's value
var evtReceiveSliderValue = 'evtSliderReturnValue' + slider_id;
$scope.$on(evtReceiveSliderValue, function(evt, params) { //Listen for the directive's response
var handle_value = params.value; //The directive will return {'value' : val}
});
To read all handle values, you need only the slider_id. The directive will return a scalar array of the handle values.
The array will be arranged in order of the handles, which should be in ascending order for the values.
This method always returns an array, even if there's only one handle, and even if you have set opts.use_array = 'false'
Sample code:
var evtReadAllSliderValues = 'evtSliderGetAllValues' + slider_id;
$scope.$broadcast(evtReadAllSliderValues, {}); //tell directive to report all values
var evtReceiveAllSliderValues = 'evtSliderReturnAllValues' + slider_id;
$scope.$on(evtReceiveAllSliderValues, function(evt, params) { //Listen for the directive's response
var values_array = params.values; //The directive will return {'values' : [num1, num2, num3... ]}
});
Option 3: Mouseup event
You can specify an opts.evt_mouseup name. If defined, an event with this name will fire whenever a handle finishes moving.
The event will come with a params object containing the value of the most recently moved handle, among other things.
See evt_mouseup in the documentation below for more details.
****************************************************************************
SETTING VALUES FROM JAVASCRIPT
To set a value on the slider, you must know the slider_id, just as with reading values.
Be careful when setting values; do not count on the directive for error checking.
Handles should stay in order; do not place the 4th handle to the left of the 3rd, for example.
Handles should be set to a valid slider value. Do not set a handle to a value outside the slider's range.
For increment sliders, be wary of placing a handle at a position that is not a valid increment.
Failing to abide by these rules will probably not cause any fatal errors, but could easily result in display problems.
The directive will auto-correct the handle if the user tries to place it outside its order or outside the slider.
The directive will not prevent you from manually setting a handle not on a valid increment, but doing so may or may not cause minor issues.
Option 1 (Recommended): Use the event.
Sample Code: Sets the leftmost handle to the value 29.3
var evtSetSliderValue = 'evtSliderSetValue' + slider_id;
$scope.$broadcast(evtSetSliderValue, {'handle' : 0, 'value' :29.3});
Option 2 (Not Recommended): Use the handle-variable you gave when defining the slider and re-init.
Ordinarily, the handle-variable should be treated as read-only. However, if you manually adjust the variable's values and then
immediately initialize the slider, the handles should adjust accordingly. In general this method will be very inefficient; use only
if you intend to re-initialize the slider anyway, and want to change the handles while you're at it.
Option 3: Prefill your variable
If your handle-variable already contains values when the slider is first built, those values will be used to position the handles.
****************************************************************************
RE-INITIALIZE THE SLIDER
To reset and reconstruct the slider, you must know the slider_id. Broadcast the event as in the sample code.
You should re-initialize the slider after adjusting any of the slider-opts in your controller. Otherwise, your changes
will not take effect. Re-initializing can also solve angular timing issues, if the directive was called before values were correctly
interpolated.
Be aware that handles will be reset upon initialization to match the values in your specified handle-variable.
If you wish to change a slider-option back to its default, you must either manually set it to its default value or delete the key from
the options array.
Note: The slider will re-initialize itself if it detects a change to its ID.
Sample Code:
var evtInitSlider = 'evtInitSlider' + slider_id;
$scope.$broadcast(evtInitSlider, {});
When the slider is finished initializing, it will emit an event that you can listen for as follows:
var evtSliderInitialized = 'evtSliderInitialized' + slider_id;
$scope.$on(evtSliderInitialized, function(evt, params)
{
//params
//values //Array of the slider's values
//id //String. This slider's id
});
****************************************************************************
A slider is composed of several elements, with the following structure. This particular example has two handles (a range slider):
<div> the container div. Holds the whole slider.
<div> the slider-bar div. Holds the actual slider itself.
<div> The slider itself. Will be as wide as the slider-bar div.
<div></div> the background-left div. The area to the left of the slider's leftmost handle.
<div></div> A handle div. This is the leftmost handle.
<div></div> Another handle.
<div></div> the background-interior div. The area between slider handles.
<div></div> the background-right div. The area to the right of the slider's rightmost handle.
<div>
<div></div> A tick on the slider
<div></div> Another tick
</div>
<div>
</div>
<div> Tick Values container
<div></div> A tick value
<div></div> A tick value
</div>
</div>
The slider may be defined using the following attributes:
REQUIRED attributes:
slider-id: A string. Use it to distinguish this slider from others when reading or writing handle values.
Note: This will be the id of the slider's container div.
Will also be used to create ids for the slider's handles so that jQuery events can be bound to them.
Ex: slider-id = 'slider1'
slider-handle-variable: A name of a variable in the parent scope. This variable will be filled with a scalar array of the values of the handles on the slider.
Handles are zero-indexed and increase from left to right. Even if there is only one handle, this will still be an ARRAY by default (see the use_array attribute).
The binding is bi-directional, i.e. changing the variable in the parent will alter a corresponding array in the slider's scope. However, I strongly recommend
that users treat the parent's variable as read-only, since changing it yourself will almost certainly not have the effect you intended in the slider, and could
potentially cause errors (unless you re-initialize the slider immediately). If you wish to change a slider value, use the method outlined under SETTING VALUES above instead.
Problems could result if this attribute is not specified for two or more sliders with the same immediate parent scope. Thus, this attribute is required.
The variable may be pre-filled with an array of default values, which will then be used to start the handles at the given positions. Be sure the values are valid.
Due to timing issues, however, I'm not necessarily convinced that this will always work as intended.
It certainly WON'T work if the variable is filled via a timeout or some other delay. It needs to be pre-filled before the directive linking function is called.
Upon initializing the slider, the handles will be set to the values stored in this variable. Beware of this when re-initializing the slider yourself.
Ex: slider-handle-variable = 'my_var'. Then, in the parent controller, you will have access to the first handle's value as $scope.my_var[0]. Default: 'handle_values'.
OPTIONAL attributes:
These should be keys in an object set to the 'slider-opts' attribute.
It is highly recommended that you define this object in your javascript controller, rather than directly in the html.
Defining it in html still works, but you may run into trouble with special character exception errors when using certain attributes (like handle_html).
Furthermore, defining it in html causes angular to fire thousands of digests whenever the user interacts with the slider.
This doesn't cause errors, but it's not good for performance. It also overflows the console's error log, which is annoying.
num_handles: Number of handles for the slider to have. A positive integer. May be input as number or string.
Ex: num_handles : '2'. Default: '1'
slider_min: Minimum value for the slider. A number. May be input as number or string.
Ex: slider_min : '25.5'. Default: '0'
slider_max: Maximum value for the slider. A number. May be input as number or string.
Ex: slider_max: '74'. Default: '100'
precision: Integer. Tells the slider how far past the decimal point to go when displaying/reporting values. Affects internal accuracy. Negative values allowed.
May be input as number or string.
A precision of 2 would cause 1.236 to be stored and reported as 1.24. A precision of -2 would cause 1234 to be stored and reported as 1200.
Ex: precision: '2'. Default: '0'
Protip: You can use this attribute to create continuous-motion sliders with power-of-ten increments.
scale_string: A ~ delimited STRING of arrays specifying the function to use to map the position on the slider to a value on the slider.
Use this attribute to define non-linear continuous sliders. Meaningless for increment sliders.
The function should be a non-decreasing mathematical function passing through (0, 0) and (1, 1), where the first coordinate represents
the slider's left% as a decimal (a number between 0 and 1, with 0 being the left edge of the slider, 1 being the right edge of the slider)
and the second represents the slider's values, linearly mapped to the interval [0, 1], with 0 = slider_min, 1 = slider_max.
Input format: "[coefficient, exponent]~[coefficient, exponent]~..."
Example: [1, .5] defines the function f(x) = 1 * x^(.5), which in turn means the slider progresses through values more quickly on the left than on the right,
with the halfway point at 25% of the slider's length. The default is a linear slider: f(x) = x
Limitations: Can only use polynomial functions. Non-integer exponents are allowed. Negative exponents are not allowed (would cause division-by-zero error).
Again, be sure that your function goes through (0, 0) and (1, 1), and is never decreasing on [0, 1], or your slider will not make sense!
Note - a strictly non-increasing function on [0, 1] passing through (0, 1) and (1, 0) would also be valid*.
*Protip: Use such a function to place the maximum on the left and the minimum on the right.
Mathematician's Protip: If you must use a non-polynomial function, use that function's Taylor series. If you don't understand Taylor series, hire a math major.
Ex: scale_string: '[1, 2]'. Default: '[1, 1]'
zero_method: String, either "newton" or "bisection". Defines what method to use when converting a slider value to a left% on the slider using the given scale polynomial.
The default behavior is "newton": Newton's method is used to find a zero. If it fails, the bisection method is then used.
Newton's method is generally significantly faster, but may fail for certain polynomials. The bisection method is slower, but guaranteed to succeed if your slider's
polynomial satisfies the criteria above, namely: non-decreasing continuous and passing through (0, 0) and (1, 1), or non-increasing continuous and passing through
(0, 1) and (1, 0).
If Newton's method is consistently failing for your function (an error message will be displayed in the console each time it fails), you can set this attribute
to "bisection" to skip Newton's method and go straight to bisection, for a performance boost.
Ex: zero_method: 'bisection'. Default: 'newton'
increment: A positive number. May be input as number or string.
If this attribute is set, the handles on the slider will snap to increments of this number,
disallowing intermediate values.
The increments are determined starting from the leftmost point of the slider (slider_min).
The maximum point of the slider need not be one of these increments.
If this attribute is set, the scale_string attribute is meaningless.
If this attribute is not set, the slider will be continous.
Make sure you have the resolution to correctly display all your increments! You can't fit 1000 points on a slider that's only 100 pixels wide.
Ex: slider-increment = '2'. Default: '0' (continuous)
user_values: A scalar array [] of values for the slider. If this attribute is specified, the slider automatically becomes an increment slider,
with the values in the array evenly spread out along it, in their given order.
Note: The increment, slider_min, slider_max, scale_string, and precision attributes are meaningless if this attribute is set.
There are several ways to define the entries of this array:
1) Make the entries the values. Ex: user_values: [25, 83, 'Stephen Colbert', 'Johnny']
2) Make the entry an object with a 'val' property. Ex: user_values: [{'val': 25}, {'val': 83}, {'val': 'Stephen Colbert'}, {'val': 'Johnny'}]
3) Make the entry an object with 'val' and 'name' properties. Ex: user_values: [{'val': 25, 'name': "Twenty-five"}, {'val': 1230, 'name':"12:30PM"}]
The 'val' property is what will be returned to the user whenever they look up a value. The 'name' property is what the slider will write to the page when
displaying a value on its own.
Regardless of the input format, all entries will be internally converted to the third format. If 'name' is undefined, 'val' is used as the 'name'.
Each entry is independent. You may use any of the three formats for an entry, regardless of the format used for neighboring entries.
Ex: user_values: '[25, {'val': 1230, 'name':"12:30PM"}, "Stephen Colbert", {'val': "Johnny"}]. This would create a slider with 4 increments. Default: ''
evt_mouseup: Name of an event to fire when a handle is released, so you can listen for it with $scope.$on elsewhere.
Also fires after the user clicks the slider to move a handle.
Ex: evt_mouseup: 'evtHandleStop'. Default: '' (no event fires)
When fired, the event will come with a params object holding the following information:
params
num_handles //Integer. Number of handles on this slider
id //String. ID of the slider
handle //Index of the most recently moved handle.
value //New value of the handle
slider_moveable: Boolean. True iff there is a chance that the slider may move about the page. May be input as boolean or string.
This is very important because moving the handles depends on the position of the mouse. When the slider is first touched, jquery is used to determine
the slider's width and horizontal offsets, so that the mouse's coordinates can be translated to a position on the slider.
If at any time after the initial definition of these offsets, the slider's position or width on the page changes, then the offsets need to be reset.
So, if this value is set to true, the slider will recalculate the offsets every time the user interacts with the slider.
Set this value to false (for a small efficiency boost) only if you are sure that the slider (and its containing div) will not move around.
Note: Re-initializing the slider will cause the offsets to be recalculated regardless. You may be able to use this to your advantage.
Ex: slider_moveable: 'false'. Default: 'true'
use_array: Boolean. False iff the slider should treat single-handle sliders as a special case, returning the value rather than a single-element array of values.
Do NOT set this attribute to 'false' if the slider has more than one handle!! This would make no sense and could also cause errors.
May be input as boolean or string.
Ex: use_array: 'false'. Default: 'true'
rotate: Number between -180 and 180. Defines how the slider should be rotated. May be input as number or string.
0 degrees is the default, unrotated. Angles increase counterclockwise: 90 degrees would make the sldier vertical, with what was the left edge at the top.
The entire slider gets rotated, including any text.
Ex: rotate: 45. Default: 0
bar_container_class: Class for the slider bar container. The (inner) width of this element will determine the width of the slider.
Note: If you set this attribute, the container will have 0 height unless you give it a height.
Ex: bar_container_class : 'my-slider-bar'. Default: 'jrg-slider-directive-bar'
left_bg_class: Class for the slider area to the left of the leftmost handle. Use to style said area.
Ex: left_bg_class : 'my-slider-left-area'. Default: 'jrg-slider-directive-bar-active'
interior_bg_class: Class for the slider area between handles. Use to style said area (does not exist if only one handle)
Ex: interior_bg_class: 'my-slider-interior-area'. Default: 'jrg-slider-directive-bar-active'
Protip: Use nth-of-type selectors to target individual interior areas if there are 3 or more handles.
right_bg_class: Class for the slider area to the right of the rightmost handle. Use to style said area.
Ex: right_bg_class: 'my-slider-right-area'. Default: 'jrg-slider-directive-bar-inactive'
handle_class: class for the handles. Use to style them.
Ex: handle_class: 'my-slider-handles'. Default: 'jrg-slider-directive-bar-handle'
Protip: Use nth-of-type selectors to target individual handles.
Note: If you're going to use your own handle styles, I strongly recommend giving the handles "margin-left: -Xpx;",
where X is half the handle's width. This will align the middle of the handle with the value it represents.
handle_html: A string of html. Use this attribute to put something inside a handle.
By default, the same html will be placed in each handle. However, you may specify different html for each handle by using a ~ delimited string.
Limitations: Can only use plain html - no angular directives or scope variables allowed, unless they are evaluated before being sent to this directive.
Exception: A handle's value can be displayed using '$$value'
Ex: handle_html: '<div class = "my-handle-interior"> </div>' //This html is applied to every single handle
Ex: handle_html: '<div> 1 </div>~<div> 2 </div>' //First handle has a 1 in it, second has a 2. Any additional handles have no inner html.
Ex: handle_html: '<div> $$value </div>' //Each handle will have its value displayed inside itself.
Default: '<div class = "jrg-slider-directive-bar-handle-inner"></div>'
units_pre: String, placed before values that the slider writes to the page.
Does not affect values returned to the user.
Ex: units_pre: '$'. Default: ''
units_post: String, placed immediately after values that the slider writes to the page.
Does not affect values returned to the user.
Ex: units_post: ' meters/second'. Default: ''
use_ticks: Boolean. True iff ticks should be shown. May be input as boolean or string.
Ex: use_ticks: 'true'. Default: 'false'
ticks_values: Array of slider values at which to display ticks, and what to display at that tick. Meaningless if use_ticks is false.
There are several ways to define the entries of this array, precisely as with user_values:
1) Make the entries the values. Ex: ticks_values: [25, 83, 47, 100]
2) Make the entry an object with a 'val' property. Ex: ticks_values: [{'val': 25}, {'val': 83}, {'val': 47}, {'val': 100}]
3) Make the entry an object with 'val' and 'name' properties. Ex: ticks_values: [{'val': 25, 'name': "Twenty-five"}, {'val': 83, 'name':"83 m/s"}]
In the first and second case, the value displayed below the tick will be the value itself prefixed by units_pre and suffixed by units_post.
In the third case, the value displayed below the tick will be exactly the 'name'.
The user is responsible for ensuring that each 'value' exists on the slider,
particularly in the case of increment sliders and sliders with user-defined values.
By default, the slider's minimum value and maximum value will be the only ticks shown.
Note: It is recommended (but not necessary) that the values in this array be sorted from least (leftmost) to greatest (rightmost).
This will keep the html in a logical order, so that nth-child selectors on the ticks' classes will make more sense.
Ex: ticks_values:[0, 25, 50, 75, 100]. Default: [slider_min, slider_max]
ticks_class: String. Class name for the ticks divs. Use to style them.
A tick is just a div. Its left edge is at the position of the specified value, inside the slider.
Protip: Use nth-of-type selectors to target individual ticks.
Ex: ticks_class: 'my-slider-ticks'. Default: 'jrg-slider-directive-ticks'
ticks_values_container_class: String. Class name for the div containing the tick values. This div has position:relative and is placed immediately
after the slider in the html, meaning it is on top of the slider itself.
Ex: ticks_values_container_class: 'my-slider-ticks-container'. Default: 'jrg-slider-directive-ticks-values-container'
ticks_value_class: String. Class name for the tick values divs. Use to style them.
These divs are absolutely positioned with their left edge aligned with the tick.
The default class gives them large widths, transparent backgrounds, top, negative margin-left (half the width), and text-align:center in order
to ensure that the value is centered below the tick. Therefore, if you use your own class,
be aware that you will have to re-position the values yourself.
Protip: Use nth-of-type selectors to target individual ticks.
Protip: Use negative 'top' css to place the tick values above the slider.
Ex: ticks_min_class: 'my-slider-ticks-value'. Default: 'jrg-slider-directive-ticks-value'
*/
angular.module('jackrabbitsgroup.angular-slider-directive', []).directive('jrgSliderDirective', ['jrgPolynomial', 'jrgSliderService', function(jrgPolynomial, jrgSliderService)
{
var template_html = '';
template_html += "<div id = '{{slider_id}}' ng-mousemove = 'mousemoveHandler($event); $event.preventDefault()' class = '{{container_class}}'>";
template_html += "<div ng-click = 'barClickHandler($event)' class = '{{bar_container_class}}' ng-style = 'bar_container_style'>";
template_html += "<div id = '{{slider_id}}SliderBar' style = 'position:relative; width:100%;'>";
template_html += "<div class = '{{left_bg_class}}' ng-style = '{\"width\": left_bg_width + \"%\", \"position\": \"absolute\", \"left\": \"0%\"}'> </div>";
template_html += "<div ng-repeat = 'handle in handles' id = '{{slider_id}}Handle{{$index}}' ng-mousedown = 'startHandleDrag($index); $event.preventDefault()' class = '{{handle_class}}' ng-style = '{\"z-index\": handle.zindex, \"left\": handle.left + \"%\", \"position\": \"absolute\"}' ng-bind-html = 'handle.innerhtml'></div>";
template_html += "<div ng-repeat = 'interior in interiors' class = '{{interior_bg_class}}' ng-style = '{\"left\": interior.left + \"%\", \"width\": interior.width + \"%\", \"position\": \"absolute\"}'> </div>";
template_html += "<div class = '{{right_bg_class}}' ng-style = '{\"width\": right_bg_width + \"%\", \"position\": \"absolute\", \"right\": \"0%\"}'> </div>";
template_html += "<div>"; //Dummy div to wrap ticks, so nth-of-type selectors will work (they ought to work without the wrapper, but don't)
template_html += "<div ng-repeat = 'tick in ticks' class = '{{ticks_class}}' ng-style = '{\"position\": \"absolute\", \"left\": tick.left + \"%\"}'> </div>"; //If use_ticks not true, scope.ticks will be empty. Thus we don't need an ng-show here.
template_html += "</div>";
template_html += "</div>";
template_html += "<div class = '{{ticks_values_container_class}}' style = 'position: relative;' ng-show = 'use_ticks'>";
template_html += "<div ng-repeat = 'tick in ticks' class = '{{ticks_value_class}}' ng-style = '{\"position\": \"absolute\", \"left\": tick.left + \"%\"}'> {{tick.name}} </div>";
template_html += "</div>";
template_html += "</div>";
template_html += "</div>";
return {
restrict: 'E',
priority: 0,
scope: {
'handle_values': '=sliderHandleVariable',
'slider_id': '@sliderId',
'slider_opts': '=sliderOpts'
},
replace: true,
template: template_html,
link: function(scope, element, attrs)
{
//variables
var ii;
var xx;
var defaults;
var building_slider; //Boolean. True iff the slider is being built.
var building_queued; //Boolean. True iff the slider needs to be rebuilt again.
var initial_values; //If the user put an array of values in their sliderHandleVariable, then initial_values will remember
//those values and set the slider's handles accordingly by default.
//If the user did not pre-fill their handle variable, initial_values will be boolean false.
var scale_function_poly; //A non-decreasing mathematical function passing through (0, 0) and (1, 1),
//where the first coordinate represents the slider's left% as a decimal
//and the second represents the slider's value, with 0 = slider_min, 1 = slider_max,
//represented as a polynomial abstract data type.
var cur_handle; //Index of handle currently being dragged.
var dragging; //Boolean. True iff we're dragging a handle.
var slider_offset; //the x and y offsets of the slider bar. Needed when translating the mouse's position to a slider position.
//slider_offset.x
//slider_offset.y
var slider_width; //the width of the slider bar. Needed when translating the mouse's position to a slider position.
var slider_init; //Boolean. True iff the slider_offset and slider_width values have been set.
var increments; //Array of valid values for an increment slider
//increments[ii]
//left //Number in [0, 100]. The left value for this increment (as % of slider width).
//value //Number in [scope.slider_min, scope.slider_max]. The value of this increment on the slider.
var user_values_flag; //Boolean. True iff the user has specified values to put on the slider
var rotate_radians; //Number. Slider's angle of rotation, converted to radians.
/*
scope variables.
scope.handles Array containing handle information
scope.handles[ii]
zindex Z-index for this handle. The leftmost handle will have the highest z-index.
When handles are near the slider's left edge, this trend is reversed; the rightmost handle has the higher z-index.
left Number between 0 and 100. The handle's % left on the slider.
value The value of the handle. A number between scope.slider_min and scope.slider_max. Directly related to the 'left' value.
display_value The value that gets displayed. Only different from 'value' for sliders with specific user-defined values.
return_value The value that gets returned. Only different from 'display_value' if the user defines it as such in user_values
innerhtml Html to place inside the handle.
html_string Raw html string (uninterpolated) to put in handle. Equal to innerhtml iff value_in_handle === false
value_in_handle Boolean. True iff the innerhtml has a '$$value' tag to interpolate.
scope.interiors Array containing info for the interior divs, between the handles. This array depends entirely on the handles.
scope.interiors[ii]
left Number in [0, 100]. Left position of this interior div (as % of slider).
width Number in [0, 100]. Width of this interior div (as % of slider).
scope.handle_values Array of handle values, linked to a variable in the parent controller.
scope.handle_values[ii] Will be identical to scope.handles[ii].display_value
The following variables represent user inputs. See the documentation above for more info.
The variable names here correspond to keys in scope.slider_opts
scope.num_handles Number of handles on the slider
scope.slider_min Minimum value of the slider
scope.slider_max Max value of the slider
scope.left_bg_class Class for slider area left of the leftmost handle
scope.interior_bg_class Class for slider area b/w handles
scope.right_bg_class Class for slider area right of rightmost handle
scope.bar_container_class Class for the slider bar container div
scope.handle_class Class for the handles
scope.units_pre Text placed before slider values
scope.units_post Text placed after slider values
scope.use_ticks Boolean. True iff the min/max values are displayed
scope.ticks_values Array of values at which to place ticks
scope.ticks_class Class for each tick div.
scope.ticks_values_container_class Class for tick values container div
scope.ticks_value_class Class for each tick value div
scope.increment Value to increment by, for increment sliders.
scope.precision Integer. Decimal precision to use when storing and reporting values.
scope.evt_mouseup Name of event to broadcast after a handle stops moving
scope.slider_moveable Boolean. True iff the slider may change location relative to the window
scope.user_values Array of values for the slider.
scope.handle_html Html string to put inside handles
scope.scale_string ~ delimited polynomial string. Defines slider's scale function
scope.zero_method String defining which method to use to find a zero.
scope.use_array Boolean. True iff the handle values are reported as an array.
scope.slider_bar_style
scope.left_bg_style
scope.interior_bg_style Holds necessary styles for the slider, backgrounds and handles. (ie. 'position:absolute;', etc.)
scope.right_bg_style
scope.handle_style
scope.left_bg_width Number in [0, 100]. Width of left background div (as % of slider).
scope.right_bg_width Number in [0, 100]. Width of right background div (as % of slider).
scope.startHandleDrag Mousedown handler for handles. Starts dragging the handle.
scope.mousemoveHandler Mousemove handler for the slider container.
scope.endHandleDrag Mouseup handler for the slider container. Ends any handle dragging.
scope.ticks Array of ticks on the slider
scope.ticks[ii]
val Value on the slider where this tick should go
name String to display for this tick
left Number in [0, 100]. The left value for this tick (as % of slider width).
scope.user_info_show Boolean. True iff the user-defined info section is shown. Default: false.
scope.user_info_html String of html, converted from info_html, defining the user-defined info section.
*/
//Define defaults
defaults =
{
'num_handles': 1,
'slider_min': 0,
'slider_max': 100,
'precision': 0,
'scale_string': '[1, 1]',
'zero_method': 'newton',
'increment': 0,
'user_values': '',
'evt_mouseup': '',
'slider_moveable': true,
'use_array': true,
'rotate': 0,
'bar_container_class': 'jrg-slider-directive-bar',
'left_bg_class': 'jrg-slider-directive-bar-active',
'interior_bg_class': 'jrg-slider-directive-bar-active',
'right_bg_class': 'jrg-slider-directive-bar-inactive',
'handle_class': 'jrg-slider-directive-bar-handle',
'handle_html': '<div class = "jrg-slider-directive-bar-handle-inner"></div>',
'units_pre': '',
'units_post': '',
'use_ticks': false,
'ticks_values': 'placeholder', //Placeholder special value
'ticks_class': 'jrg-slider-directive-ticks',
'ticks_values_container_class': 'jrg-slider-directive-ticks-values-container',
'ticks_value_class': 'jrg-slider-directive-ticks-value'
};
//Init the event name variables here so we don't get undefined reference errors. Will be properly set later.
var evt_names =
{
'evt_get_value': '',
'evt_return_value': '',
'evt_get_all_values': '',
'evt_return_all_values': '',
'evt_set_value': '',
'evt_init_slider': '',
'evt_init_slider_finished': ''
};
//Holds functions that deregister the event listeners. Initialize to blank functions here.
var evt_deregister =
{
'evt_get_value': function() {},
'evt_get_all_values': function() {},
'evt_set_value': function() {},
'evt_init_slider': function() {},
};
scale_function_poly = jrgPolynomial.stringToPoly('[1, 1]'); //Init to identity, avoid undefined errors.
//Initialize and build the slider. Can't allow values to change during computation.
// If an attempt is made to re-init the slider while it is in the process of building,
// building_queued will be set to true, and the slider will re-init again upon completion.
// This may be somewhat inefficient, but it is the only realistic and reliable way to ensure there are no fatal errors.
var initSlider = function()
{
building_slider = true;
building_queued = false;
//Fill info
for(var xx in defaults)
{
if(scope.slider_opts[xx] === undefined || scope.slider_opts[xx] === null)
{
scope[xx] = defaults[xx];
}
else
{
scope[xx] = scope.slider_opts[xx];
}
}
if(scope.ticks_values == 'placeholder') //If this wasn't set by the user
{
//Define the default. Can't put this is the defaults array because it depends on the user's min and max values.
if(scope.user_values.length > 0)
{
scope.ticks_values = [scope.user_values[0], scope.user_values[scope.user_values.length - 1]];
}
else
{
scope.ticks_values = [scope.slider_min, scope.slider_max];
}
}
setInterfaceEvents(); //Set the events
jrgSliderService.register(scope.slider_id, endHandleDrag); //Register the slider with the service
scope.initial_values = false;
if(!scope.handle_values)
{
scope.use_array = parseBoolean(scope.use_array, defaults.use_array); //Must parse before using.
if(scope.use_array === false) //Arbitrarily treat single handle as special case, to bypass 1-element array.
{
scope.handle_values = ''; //init to empty string in this case
}
else
{
scope.handle_values = [];
}
}
else
{
//Arbitrarily treat single handle as special case, to bypass 1-element array.
if(isArray(scope.handle_values) === false) //Check for array here; use_array may not be correctly defined yet, and the user ought to have it in the format they intend to use.
{
scope.initial_values = scope.handle_values;
}
else
{
if(scope.handle_values.length !== undefined && scope.handle_values.length > 0) //User may have initialized to empty array; initial_values should be left false in this case.
{
//copy handle_values
var array_copy = [];
for(ii = 0; ii < scope.handle_values.length; ii++)
{
array_copy[ii] = scope.handle_values[ii];
}
scope.initial_values = array_copy;
}
}
}
//Call the helpers to build the slider
parseData();
setStyles();
setHandles();
if(scope.use_ticks === true) //Form ticks if necessary. Do nothing if the ticks are hidden.
{
setTicks();
}
setJqueryTouch();
building_slider = false;
//If an attempt was made to re-init the slider while it was building, re-init now.
if(building_queued === true)
{
initSlider();
}
else
{
scope.$emit(evt_names.evt_init_slider_finished, {'id':scope.slider_id, 'values':scope.handle_values});
}
};
//Setup Functions
var parseData = function()
{
//Parse numbers
scope.num_handles = parseInt(scope.num_handles, 10);
scope.slider_min = parseFloat(scope.slider_min);
scope.slider_max = parseFloat(scope.slider_max);
scope.increment = parseFloat(scope.increment);
scope.precision = parseInt(scope.precision, 10);
scope.rotate = reRangeAngle(parseFloat(scope.rotate));
//Parse Booleans
scope.slider_moveable = parseBoolean(scope.slider_moveable, defaults.slider_moveable);
scope.use_array = parseBoolean(scope.use_array, defaults.use_array);
user_values_flag = false;
//If set, parse values and re-define other values
if(scope.user_values !== '' && scope.user_values)
{
user_values_flag = true;
for(ii = 0; ii < scope.user_values.length; ii++)
{
if(scope.user_values[ii].val === undefined || scope.user_values[ii].val === null) //If val is undefined, then the entry itself is the value.
{
var temp_val = scope.user_values[ii];
scope.user_values[ii] = {'val':temp_val, 'name':temp_val};
}
else if(scope.user_values[ii].name === undefined || scope.user_values[ii].name === null)
{
scope.user_values[ii].name = scope.user_values[ii].val;
}
}
//set up slider numbers so that the value on the slider corresponds to the index of the appropriate value in user_values
scope.slider_min = 0;
scope.slider_max = scope.user_values.length - 1;
scope.increment = 1;
scope.precision = 0;
}
//Initialize variables
scope.left_bg_width = 0;
scope.right_bg_width = 0;
cur_handle = 0;
dragging = false;
scope.recent_dragging = false;
scope.handles = [];
scope.interiors = [];
scope.ticks = [];
increments = [];
slider_offset = {'x': 0, 'y': 0}; //Init to 0; will set later
slider_width = 100; //Init to 100; will set later
slider_init = false;
rotate_radians = scope.rotate * (2 * Math.PI / 360);
//Compute slope of slider and slope of perpendicular. Conceptually it makes more sense to compute this
//at the same time that we set the slider offsets, but that code may be run many times, and these won't change.
//Thus, it's more efficient to compute these now.
if(scope.rotate !== 0 && scope.rotate !== 90 && scope.rotate !== -90 && scope.rotate !== 180)
{
//Ignore slopes for horizontal and vertical sliders, because they produce division-by-zero error.
slider_offset.m1 = Math.tan(rotate_radians);
slider_offset.m2 = (-1 / slider_offset.m1);
}
//Parse scale, form scale function
if(scope.increment === 0) //If not increment slider, re-form scale polynomial
{
scale_function_poly = jrgPolynomial.stringToPoly(scope.scale_string);
}
}; //end parseData
//Boolean parser helper - string to boolean.
var parseBoolean = function(bool, default_val)
{
if(bool == 'false' || bool === false)
{
return false;
}
else if(bool == 'true' || bool === true)
{
return true;
}
else
{
return default_val;
}
};
var setStyles = function()
{
/* Now handled in the template directly via ng-style, for IE compatibility
//Setup needed bar styles
scope.left_bg_style = 'position:absolute; left:0%;'; //width varies depending on handle position; define separately.
scope.interior_bg_style = 'position:absolute;'; //left, width varies depending on handles; define separately.
scope.right_bg_style = 'position:absolute; right:0%;'; //width varies depending on handle position; define separately.
scope.handle_style = 'position:absolute;';
*/
// var ro = 'rotate(' + scope.rotate + 'deg); ';
// scope.bar_container_style = '-moz-transform:' + ro + '-webkit-transform:' + ro + '-o-transform:' + ro + '-ms-transform:' + ro + 'transform:' + ro;
//ng-style requires object format
var ro = 'rotate(' + scope.rotate + 'deg)';
scope.bar_container_style = {'-moz-transform': ro, '-webkit-transform': ro, '-o-transform': ro, '-ms-transform': ro, 'transform': ro};
}; //End setStyles
var setHandles = function()
{
//Set up handles
//Parse handle html, fill handle_htmls array with html for each handle.
var handle_htmls;
if(scope.handle_html.indexOf('~') != -1) //If the user specified individual html for each handle
{
handle_htmls = scope.handle_html.split('~');
for(ii = handle_htmls.length; ii < scope.num_handles; ii++)
{
handle_htmls[ii] = ''; //Blank out the rest of the array if necessary
}
}
else
{
//Either scope.handle_html is the default, or it is the user-defined html. Either way, it should be applied to every handle.
handle_htmls = [];
for(ii = 0; ii < scope.num_handles; ii++)
{
handle_htmls[ii] = scope.handle_html;
}
}
//Now fill scope.handles
for(ii = 0; ii < scope.num_handles; ii++)
{
var left_val;
if(scope.num_handles == 1) //Need to check this case to avoid division by zero.
{
left_val = 0;
scope.right_bg_width = 100; //Also, in this case, there is no handle on the right, so the right background does not have 0 width. Might as well update it here.
}
else
{
left_val = (100 / (scope.num_handles - 1)) * ii; //Start the handles evenly spread out on the bar
}
var value_in_handle = false;
if(handle_htmls[ii].indexOf('$$value') != -1)
{
value_in_handle = true;
}
scope.handles[ii] =
{
'zindex' : 10, //placeholder value
'left' : left_val,
'value' : calculate_value(left_val), //Calculate value based on position
'html_string': handle_htmls[ii],
'value_in_handle': value_in_handle
};
if(user_values_flag === false)
{
scope.handles[ii].display_value = scope.handles[ii].value;
scope.handles[ii].return_value = scope.handles[ii].value;
}
else
{
scope.handles[ii].display_value = scope.user_values[scope.handles[ii].value].name;
scope.handles[ii].return_value = scope.user_values[scope.handles[ii].value].val;
}
if(scope.use_array === false) //Arbitrarily treat single handle as special case, to bypass 1-element array.
{
scope.handle_values = scope.handles[ii].return_value; //link to parent scope variable
}
else
{
scope.handle_values[ii] = scope.handles[ii].return_value; //link to parent scope variable
}
update_zindex(ii); //Set the zindex field properly
//set innerhtml field
if(scope.handles[ii].value_in_handle === true) //Interpolate innerhtml if necessary
{
parseHandleHtml(ii);
}
else
{
scope.handles[ii].innerhtml = scope.handles[ii].html_string;
}
}
//Set up interiors - must define them now, before we try to move any handles
for(ii = 0; ii < scope.num_handles - 1; ii++)
{
scope.interiors[ii] =
{
'left' : scope.handles[ii].left, //interior div has same left position as handle on its left
'width' : scope.handles[ii+1].left - scope.handles[ii].left
};
}
//Set up increments if necessary
if(scope.increment !== 0 && scope.increment) //If this is an increment slider
{
var cur_val = scope.slider_min;
for(ii=0; cur_val < scope.slider_max; ii++)
{
increments[ii] = {};
increments[ii].value = cur_val;
increments[ii].left = calculate_left(cur_val);
cur_val += scope.increment;
}
increments[ii] = {};
increments[ii].value = scope.slider_max;
increments[ii].left = 100;
if(scope.initial_values === false) //If the user pre-filled their values, don't bother with this section, we're going to move every handle again anyway.
{
//Now, move each handle to the nearest valid increment
//Cannot simply use findNearestIncrement and moveHandle, because this might try to move a handle beyond its adjacent handles.
//We must move the handles in order of which is closest to its nearest increment
//Recall that, at this point, the handles are evenly spaced along the slider.
var distances_to_increment = [];
for(ii = 0; ii < scope.num_handles; ii++)
{
var new_left = findNearestIncrement(scope.handles[ii].left);
distances_to_increment[ii] =
{
'handle' : ii,
'distance' : Math.abs(scope.handles[ii].left - new_left),
'new_left' : new_left
};
}
distances_to_increment.sort(function(a, b)
{
if(a.distance < b.distance)
{
return -1;
}
else if(b.distance < a.distance)
{
return 1;
}
else
{
return 0;
}
});
for(ii = 0; ii < scope.num_handles; ii++)
{
moveHandle(distances_to_increment[ii].handle, distances_to_increment[ii].new_left);
}
}
}
if(scope.initial_values === false) //Requires '===' test here. Equality in js is weird: ([0] != false) returns false!
{} //Do nothing
else //If the user pre-filled their handle values, need to move the handles accordingly.
{
if(evt_names.evt_set_value === '' || evt_names.evt_set_value === undefined || evt_names.evt_set_value === null)
{
setInterfaceEvents(); //Make sure the event name is set.
}
for(ii=0; ii < scope.num_handles; ii++) //Go through each handle, set it using the normal set function, just like set event listener
{
if(scope.use_array === false)
{
setHandleValue(ii, scope.initial_values);
}
else
{
setHandleValue(ii, scope.initial_values[ii]);
}
}
}
}; //End setHandles
//setTicks: fills scope.ticks with necessary information. Requires setHandles to have run first.
var setTicks = function()
{
for(var ii = 0; ii < scope.ticks_values.length; ii++)
{
if(scope.ticks_values[ii].val === undefined || scope.ticks_values[ii].val === null) //If val is undefined, then the entry itself is the value.
{
scope.ticks[ii] = {'val':scope.ticks_values[ii], 'name': scope.units_pre + scope.ticks_values[ii] + scope.units_post};
}
else if(scope.ticks_values[ii].name === undefined || scope.ticks_values[ii].name === null) //If val defined, name undefined
{
scope.ticks[ii] = {'val':scope.ticks_values[ii].val, 'name': scope.units_pre + scope.ticks_values[ii].val + scope.units_post};
}
else //Both val and name defined
{
scope.ticks[ii] = {'val':scope.ticks_values[ii].val, 'name': scope.ticks_values[ii].name};
}
//Calculate this tick's left %
var new_left;
if(user_values_flag === true)
{
var index;
var jj;
//Find the tick value in the user_values array to get the index of the appropriate increment where this tick should be placed
for(jj = 0; jj < scope.user_values.length; jj++)
{
if(scope.user_values[jj].val.toString() == scope.ticks[ii].val.toString())
{
index = jj;
jj = scope.user_values.length; //Stop looping
}
}
new_left = increments[index].left;
}
else
{
new_left = calculate_left(scope.ticks[ii].val); //No user-defined values; calculate left normally.
}
scope.ticks[ii].left = new_left;
}
}; //End setTicks
var setJqueryTouch = function()
{
//initTouch: Function wrapper for timeout - waits until angular applies ids to elements, then sets up jquery touch events