This repository has been archived by the owner on Dec 3, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 124
/
Copy pathangular-toggle-switch.js
84 lines (73 loc) · 2.42 KB
/
angular-toggle-switch.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
(function() {
var module = angular.module('toggle-switch', ['ng']);
module.provider('toggleSwitchConfig', [function() {
this.onLabel = 'On';
this.offLabel = 'Off';
this.knobLabel = '\u00a0';
var self = this;
this.$get = function() {
return {
onLabel: self.onLabel,
offLabel: self.offLabel,
knobLabel: self.knobLabel
};
};
}]);
module.directive('toggleSwitch',['toggleSwitchConfig', function (toggleSwitchConfig) {
return {
restrict: 'EA',
replace: true,
require:'ngModel',
scope: {
disabled: '@',
onLabel: '@',
offLabel: '@',
knobLabel: '@'
},
template: '<div role="radio" class="toggle-switch" ng-class="{ \'disabled\': disabled }">' +
'<div class="toggle-switch-animate" ng-class="{\'switch-off\': !model, \'switch-on\': model}">' +
'<span class="switch-left" ng-bind="onLabel"></span>' +
'<span class="knob" ng-bind="knobLabel"></span>' +
'<span class="switch-right" ng-bind="offLabel"></span>' +
'</div>' +
'</div>',
compile: function(element, attrs) {
if (!attrs.onLabel) { attrs.onLabel = toggleSwitchConfig.onLabel; }
if (!attrs.offLabel) { attrs.offLabel = toggleSwitchConfig.offLabel; }
if (!attrs.knobLabel) { attrs.knobLabel = toggleSwitchConfig.knobLabel; }
return this.link;
},
link: function(scope, element, attrs, ngModelCtrl){
var KEY_SPACE = 32;
element.on('click', function() {
scope.$apply(scope.toggle);
});
element.on('keydown', function(e) {
var key = e.which ? e.which : e.keyCode;
if (key === KEY_SPACE) {
scope.$apply(scope.toggle);
$event.preventDefault();
}
});
ngModelCtrl.$formatters.push(function(modelValue){
return modelValue;
});
ngModelCtrl.$parsers.push(function(viewValue){
return viewValue;
});
ngModelCtrl.$viewChangeListeners.push(function() {
scope.$eval(attrs.ngChange);
});
ngModelCtrl.$render = function(){
scope.model = ngModelCtrl.$viewValue;
};
scope.toggle = function toggle() {
if(!scope.disabled) {
scope.model = !scope.model;
ngModelCtrl.$setViewValue(scope.model);
}
};
}
};
}]);
})();