mirror of
https://github.com/ionic-team/ionic-framework.git
synced 2026-03-13 10:22:08 +08:00
96 lines
2.8 KiB
JavaScript
96 lines
2.8 KiB
JavaScript
/**
|
|
* @ngdoc directive
|
|
* @name ionToggle
|
|
* @module ionic
|
|
* @codepen tfAzj
|
|
* @restrict E
|
|
*
|
|
* @description
|
|
* A toggle is an animated switch which binds a given model to a boolean.
|
|
*
|
|
* Allows dragging of the switch's nub.
|
|
*
|
|
* The toggle behaves like any [AngularJS checkbox](http://docs.angularjs.org/api/ng/input/input[checkbox]) otherwise.
|
|
*
|
|
* @param toggle-class {string=} Sets the CSS class on the inner `label.toggle` element created by the directive.
|
|
*
|
|
* @usage
|
|
* Below is an example of a toggle directive which is wired up to the `airplaneMode` model
|
|
* and has the `toggle-calm` CSS class assigned to the inner element.
|
|
*
|
|
* ```html
|
|
* <ion-toggle ng-model="airplaneMode" toggle-class="toggle-calm">Airplane Mode</ion-toggle>
|
|
* ```
|
|
*/
|
|
IonicModule
|
|
.directive('ionToggle', [
|
|
'$ionicGesture',
|
|
'$timeout',
|
|
function($ionicGesture, $timeout) {
|
|
|
|
return {
|
|
restrict: 'E',
|
|
replace: true,
|
|
require: '?ngModel',
|
|
scope: {
|
|
ngModel: '=?',
|
|
ngValue: '=?',
|
|
ngChecked: '=?',
|
|
ngChange: '&',
|
|
ngDisabled: '=?'
|
|
},
|
|
transclude: true,
|
|
template: '<div class="item item-toggle">' +
|
|
'<div ng-transclude></div>' +
|
|
'<label class="toggle">' +
|
|
'<input type="checkbox" ng-model="ngModel" ng-value="ngValue" ng-change="ngChange()" ng-disabled="ngDisabled">' +
|
|
'<div class="track">' +
|
|
'<div class="handle"></div>' +
|
|
'</div>' +
|
|
'</label>' +
|
|
'</div>',
|
|
|
|
compile: function(element, attr) {
|
|
var input = element.find('input');
|
|
if(attr.name) input.attr('name', attr.name);
|
|
if(attr.ngChecked) input.attr('ng-checked', 'ngChecked');
|
|
if(attr.ngTrueValue) input.attr('ng-true-value', attr.ngTrueValue);
|
|
if(attr.ngFalseValue) input.attr('ng-false-value', attr.ngFalseValue);
|
|
if(attr.toggleClass) {
|
|
element[0].getElementsByTagName('label')[0].classList.add(attr.toggleClass);
|
|
}
|
|
|
|
return function($scope, $element, $attr) {
|
|
var el, checkbox, track, handle;
|
|
|
|
el = $element[0].getElementsByTagName('label')[0];
|
|
checkbox = el.children[0];
|
|
track = el.children[1];
|
|
handle = track.children[0];
|
|
|
|
var ngModelController = angular.element(checkbox).controller('ngModel');
|
|
|
|
$scope.toggle = new ionic.views.Toggle({
|
|
el: el,
|
|
track: track,
|
|
checkbox: checkbox,
|
|
handle: handle,
|
|
onChange: function() {
|
|
if(checkbox.checked) {
|
|
ngModelController.$setViewValue(true);
|
|
} else {
|
|
ngModelController.$setViewValue(false);
|
|
}
|
|
$scope.$apply();
|
|
}
|
|
});
|
|
|
|
$scope.$on('$destroy', function() {
|
|
$scope.toggle.destroy();
|
|
});
|
|
};
|
|
}
|
|
|
|
};
|
|
}]);
|