forked from xpepermint/angular-ui-switch
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathangular-ui-switch.js
More file actions
72 lines (70 loc) · 2.81 KB
/
angular-ui-switch.js
File metadata and controls
72 lines (70 loc) · 2.81 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
64
65
66
67
68
69
70
71
72
angular.module('uiSwitch', [])
.directive('switch', function($compile, $parse){
return {
require: 'ngModel'
, restrict: 'AE'
, replace: true
, transclude: true
, scope: {
isDisabled: '@',
ngModel: '=',
ngChange: '@'
}
, controller: function($scope){
$scope.updateSwitch = function(element){
//set style
$scope.setElementStyle(element);
};
$scope.setElementStyle = function(element){
if($scope.ngModel){
element.addClass('checked');
}else{
element.removeClass('checked');
}
};
}
, template: function(element, attrs) {
var html = '';
html += '<span';
html += ' class="switch' + (attrs.class ? ' ' + attrs.class : '') + '"';
html += '>';
html += '<small></small>';
html += '<input type="checkbox"';
html += attrs.id ? ' id="' + attrs.id + '"' : '';
html += attrs.name ? ' name="' + attrs.name + '"' : '';
html += attrs.ngModel ? ' ng-model="' + attrs.ngModel + '"' : '';
html += ' style="display:none" />';
html += '<span class="switch-text">'; //adding new container for switch text
html += attrs.on ? '<span class="on">'+attrs.on+'</span>' : ''; //switch text on value set by user in directive html markup
html += attrs.off ? '<span class="off">'+attrs.off + '</span>' : ' '; //switch text off value set by user in directive html markup
html += '</span>';
return html;
}
, link: function($scope, element, attrs, controller){
//apply initial style
$scope.setElementStyle(element);
//add click event when not disabled
if(!angular.isDefined(attrs.isDisabled) || attrs.isDisabled == 'false'){
element.bind('click', function(event){
$scope.$apply(function(){
$scope.ngModel = !$scope.ngModel; //toggle
});
if($scope.ngChange){
$scope.$parent[$scope.ngChange]();
}
});
//add watch
$scope.$watch(
function(){
return $scope.ngModel;
},
function(newValue, oldValue){
if(newValue != oldValue){
$scope.updateSwitch(element);
}
}
);
}
}
}
});