Last active
January 10, 2018 05:00
-
-
Save dave-newson/f6c5e9c2f3bc315e292c to your computer and use it in GitHub Desktop.
Bootstrap-toggle AngularJS directive
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
'use strict'; | |
/** | |
* Bootstrap-toggle Directive | |
* @link https://github.com/minhur/bootstrap-toggle | |
*/ | |
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(); | |
}); | |
// Initialise BootstrapToggle | |
$element.bootstrapToggle(); | |
} | |
}; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks Dave. Here's the version with ngDisabled that jjmontesl created but not available on gist anymore: https://gist.github.com/grenoult/20ddc6c23d6f06580fce9803521f1ea6