Created
July 24, 2014 06:04
-
-
Save bjcull/8ff8611f5b39978e5134 to your computer and use it in GitHub Desktop.
Angular directive for bootstrap-switch | http://www.bootstrap-switch.org/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.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); | |
} | |
}); | |
} | |
}; | |
} | |
]); |
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
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?