forked from JumpLink/angular-toggle-switch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathangular-toggle-switch.js
65 lines (57 loc) · 2.33 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
angular.module('toggle-switch', ['ng']).directive('toggleSwitch', function ($compile) {
return {
restrict: 'EA',
replace: true,
scope: {
model: '=',
disabled: '@',
onLabel: '@',
offLabel: '@',
knobLabel: '@',
html: '='
},
template: '<div class="switch" ng-click="toggle()" ng-class="{ \'disabled\': disabled }"><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: function($scope) {
$scope.toggle = function toggle() {
if(!$scope.disabled) {
$scope.model = !$scope.model;
}
};
},
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.disabled)) { attrs.disabled = 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);
});
};
}
};
});