Skip to content

Instantly share code, notes, and snippets.

@christianhanvey
Created April 16, 2014 07:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save christianhanvey/10821199 to your computer and use it in GitHub Desktop.
Save christianhanvey/10821199 to your computer and use it in GitHub Desktop.
angular radio switch directive - an on/off switch
window.app = angular.module('mainApp', []);
app.controller('mainCtrl', function ($scope) {
$scope.include = 'yes';
});
app.directive('radioSwitch', ['analyticsSettings', function (analyticsSettings) {
return {
restrict: 'A',
scope: {
onVal: '@radioSwitchOn',
offVal: '@radioSwitchOff',
radioSwitchModel: '='
},
templateUrl: analyticsSettings.partialPath + 'radio-switcher.tpl.html',
link: function (scope, elem, attrs) {
if (attrs.radioSwitchDefaultState) {
scope.radioSwitchModel = (attrs.radioSwitchDefaultState == 'off') ? scope.offVal : scope.onVal;
safeApply();
}
elem.on('click', function () {
scope.radioSwitchModel = (scope.radioSwitchModel == scope.onVal) ? scope.offVal : scope.onVal;
safeApply();
});
}
}
}]);
<p>Radio Switcher</p>
<br/>
<input type="radio" name="includeExclude" value="yes" ng-model="include" /> Include
<input type="radio" name="includeExclude" value="no" ng-model="include" /> Exclude
<br/>
<hr/>
<div class="radio-switcher"
data-radio-switch
data-radio-switch-model="include"
data-radio-switch-on="yes"
data-radio-switch-off="no"
data-radio-switch-default-state="on">
</div>
<hr/>
<div class="radio-switcher radio-switcher2"
data-radio-switch
data-radio-switch-model="include2"
data-radio-switch-on="yes"
data-radio-switch-off="no">
</div>
<hr/>
<div class="radio-switcher radio-switcher3"
data-radio-switch
data-radio-switch-model="include3"
data-radio-switch-on="include"
data-radio-switch-off="exclude"
data-radio-switch-default-state="off">
</div>
body {
background: #fff;
padding: 2em;
}
.radio-switcher {
box-sizing: border-box;
overflow: auto;
padding: 3px; /* box-shadow width */
}
.radio-switcher-switch {
border-radius: 10px;
height: 20px;
width: 40px;
padding: 3px;
transition: all 0.5s ease-out;
box-shadow: 0px 0px 0px 2px #fff, 0px 0px 0px 3px #ccc;
background-color: #ccc;
float: left;
margin-right: 1em;
}
.radio-switcher-switch:hover {
cursor: pointer;
}
.radio-switcher-switch.on {
background-color: red;
}
.radio-switcher-switch.off {
background-color: green;
}
.radio-switcher-switch:before {
content: ' ';
display: block;
border-radius: 7px;
width: 50%;
height: 14px;
background-color: white;
transition: all 0.15s ease-out;
position: relative;
left: 25%;
}
.radio-switcher-switch.on:before {
left: 50%;
}
.radio-switcher-switch.off:before {
left: 0;
}
.radio-switcher2 .radio-switcher-switch {
width: 80px;
}
.radio-switcher3 .radio-switcher-switch {
width: 160px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment