Skip to content

Instantly share code, notes, and snippets.

@jvelo
Created February 15, 2013 20:31
Show Gist options
  • Save jvelo/4963309 to your computer and use it in GitHub Desktop.
Save jvelo/4963309 to your computer and use it in GitHub Desktop.
Small directive to create an AngularJS switch button with Twitter Bootstrap + jQuery
myApp.directive('switchButton', function() {
return {
require: 'ngModel',
restrict: 'E',
template: '<div class="btn-group">' +
'<button class="btn on" ng-click="on()"></button>' +
'<button class="btn off" ng-click="off()"></button>' +
'</div>',
link: function($scope, element, attrs, controller) {
$scope.on = function() {
$(element).find(".btn.on").addClass("btn-primary");
$(element).find(".btn.off").removeClass("btn-primary");
controller.$setViewValue(true);
}
$scope.off = function() {
$(element).find(".btn.off").addClass("btn-primary");
$(element).find(".btn.on").removeClass("btn-primary");
controller.$setViewValue(false);
}
controller.$render = function() {
$scope[controller.$viewValue ? "on" : "off"]();
};
}
}
});
<switch-button ng-model="light"></switch-button>
Light : <span ng-bind="light"></span>
switch-button button {
height: 18px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment