Skip to content

Instantly share code, notes, and snippets.

@bjcull
Created July 24, 2014 06:04
Show Gist options
  • Save bjcull/8ff8611f5b39978e5134 to your computer and use it in GitHub Desktop.
Save bjcull/8ff8611f5b39978e5134 to your computer and use it in GitHub Desktop.
Angular directive for bootstrap-switch | http://www.bootstrap-switch.org/
.directive('bootstrapSwitch', [
function() {
return {
restrict: 'A',
require: '?ngModel',
link: function(scope, element, attrs, ngModel) {
element.bootstrapSwitch();
element.on('switchChange.bootstrapSwitch', function(event, state) {
if (ngModel) {
scope.$apply(function() {
ngModel.$setViewValue(state);
});
}
});
scope.$watch(attrs.ngModel, function(newValue, oldValue) {
if (newValue) {
element.bootstrapSwitch('state', true, true);
} else {
element.bootstrapSwitch('state', false, true);
}
});
}
};
}
]);
@mota57
Copy link

mota57 commented Jul 2, 2016

Thanks

@jaspalt
Copy link

jaspalt commented Jul 29, 2016

Thanks for this directive Ben.

I wanted to know what exactly are you doing with the $watch scope. I didn't know the bootstrapSwitch function took 2 parameters as the state. In your case, you have it as true, true and false, true.

Do you mind explaining?

@geoffreybauduin
Copy link

You should use this watcher instead of the one you are using if you want to use a pre-defined value

scope.$watch(function () {
  return ngModel && ngModel.$viewValue;
}, function(newValue, oldValue) {
  if (newValue) {
    element.bootstrapSwitch('state', true, true);
  } else {
    element.bootstrapSwitch('state', false, true);
  }
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment