forked from cgarvis/angular-toggle-switch
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathangular-toggle-switch.js
More file actions
63 lines (59 loc) · 2 KB
/
angular-toggle-switch.js
File metadata and controls
63 lines (59 loc) · 2 KB
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
angular.module('toggle-switch', ['ng']).directive('toggleSwitch', function () {
return {
restrict: 'EA',
replace: true,
require:'ngModel',
scope: {
disabled: '@',
onLabel: '@',
offLabel: '@',
knobLabel: '@',
onValue: '@',
offValue: '@'
},
template: '<div role="radio" class="switch" ng-class="{ \'disabled\': disabled }">' +
'<div class="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>',
link: function(scope, element, attrs, ngModelCtrl){
if (!attrs.onLabel) { attrs.onLabel = 'On'; }
if (!attrs.offLabel) { attrs.offLabel = 'Off'; }
if (!attrs.knobLabel) { attrs.knobLabel = '\u00a0'; }
if (!attrs.disabled) { attrs.disabled = false; }
if (!attrs.onValue) { attrs.onValue = true; }
if (!attrs.offValue) { attrs.offValue = false; }
//if values are number
if((+attrs.onValue).toString() === attrs.onValue && (+attrs.offValue).toString() === attrs.offValue) {
attrs.onValue = parseInt(attrs.onValue);
attrs.offValue = parseInt(attrs.offValue);
}
element.on('click', function() {
scope.$apply(scope.toggle);
});
ngModelCtrl.$formatters.push(function(modelValue){
if(attrs.onValue === modelValue) {
return true;
}
return false;
});
ngModelCtrl.$parsers.push(function(viewValue){
if(viewValue) {
return attrs.onValue;
}
return attrs.offValue;
});
ngModelCtrl.$render = function(){
scope.model = ngModelCtrl.$viewValue;
};
scope.toggle = function toggle() {
if(!scope.disabled) {
scope.model = !scope.model;
ngModelCtrl.$setViewValue(scope.model);
}
};
}
};
});