Skip to content

Instantly share code, notes, and snippets.

@grenoult
Created January 10, 2018 04:59
Show Gist options
  • Save grenoult/20ddc6c23d6f06580fce9803521f1ea6 to your computer and use it in GitHub Desktop.
Save grenoult/20ddc6c23d6f06580fce9803521f1ea6 to your computer and use it in GitHub Desktop.
Bootstrap-toggle AngularJS directive
'use strict';
/**
* Bootstrap-toggle Directive
* Forked from from: https://gist.github.com/dave-newson/f6c5e9c2f3bc315e292c
* This version supports ngDisabled directive.
* Unashamedly coped from https://gist.github.com/jjmontesl/54457bf1342edeb218b7 as it is not available anymore.
*/
angular.module('togglecheckbox', [])
.directive('toggleCheckbox', function() {
/**
* Directive
*/
return {
restrict: 'A',
transclude: true,
replace: false,
require: 'ngModel',
link: function ($scope, $element, $attr, require) {
var ngModel = require;
// update model from Element
var updateModelFromElement = function() {
// If modified
var checked = $element.prop('checked');
if (checked != ngModel.$viewValue) {
// Update ngModel
ngModel.$setViewValue(checked);
$scope.$apply();
}
};
// Update input from Model
var updateElementFromModel = function() {
// Update button state to match model
$element.trigger('change');
};
// Observe: Element changes affect Model
$element.on('change', function() {
updateModelFromElement();
});
// Observe: ngModel for changes
$scope.$watch(function() {
return ngModel.$viewValue;
}, function() {
updateElementFromModel();
});
// Observe: disabled attribute set by ngDisabled
$scope.$watch(function() {
return $($element).attr('disabled');
}, function(newVal) {
$($element).bootstrapToggle(! newVal ? "enable" : "disable");
});
// Initialise BootstrapToggle
$element.bootstrapToggle();
}
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment