forked from JumpLink/angular-toggle-switch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
angular-toggle-switch.js
76 lines (69 loc) · 2.96 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
angular.module('toggle-switch', ['ng']).directive('toggleSwitch', ['$compile', function($compile) {
return {
restrict: 'EA',
replace: true,
scope: {
model: '=',
isDisabled: '@',
onLabel: '@',
offLabel: '@',
knobLabel: '@',
html: '=',
onChange: '&'
},
template: '<div class="ats-switch" ng-click="toggle()" ng-class="{ \'disabled\': isDisabled }"><div class="switch-animate" ng-class="{\'switch-off\': !model, \'switch-on\': model}"><span class="switch-left"></span><span class="knob"></span><span class="switch-right"></span></div></div>',
controller: ['$scope', function($scope) {
$scope.toggle = function toggle() {
if (!$scope.isDisabled) {
$scope.model = !$scope.model;
}
$scope.onChange();
};
}],
compile: function(element, attrs) {
if (angular.isUndefined(attrs.onLabel)) {
attrs.onLabel = 'On';
}
if (angular.isUndefined(attrs.offLabel)) {
attrs.offLabel = 'Off';
}
if (angular.isUndefined(attrs.knobLabel)) {
attrs.knobLabel = '\u00a0';
}
if (angular.isUndefined(attrs.isDisabled)) {
attrs.isDisabled = false;
}
if (angular.isUndefined(attrs.html)) {
attrs.html = false;
}
return function postLink(scope, iElement, iAttrs, controller) {
var bindSpan = function(span, html) {
span = angular.element(span);
var bindAttributeName = (html === true) ? 'ng-bind-html' : 'ng-bind';
// remove old ng-bind attributes
span.removeAttr('ng-bind-html');
span.removeAttr('ng-bind');
if (angular.element(span).hasClass("switch-left"))
span.attr(bindAttributeName, 'onLabel');
if (span.hasClass("knob"))
span.attr(bindAttributeName, 'knobLabel');
if (span.hasClass("switch-right"))
span.attr(bindAttributeName, 'offLabel');
$compile(span)(scope, function(cloned, scope) {
span.replaceWith(cloned);
});
};
// add ng-bind attribute to each span element.
// NOTE: you need angular-sanitize to use ng-bind-html
var bindSwitch = function(iElement, html) {
angular.forEach(iElement[0].children[0].children, function(span, index) {
bindSpan(span, html);
});
};
scope.$watch('html', function(newValue) {
bindSwitch(iElement, newValue);
});
};
}
};
}]);