I'm currently working on creating a custom directive in Angular that transforms a tag into a toggle button, similar to a checkbox. As of now, the code I've developed updates the internal variable within isolated scope, but bidirectional binding doesn't seem to be functioning properly. Although clicking the button triggers the toggling effect (the CSS class is being added and removed), the value of myVariable
isn't being updated.
Any assistance would be greatly appreciated!
How to Use:
<button toggle-button="myVariable">My Button</button>
Directive Implementation:
(function() {
var directive = function () {
return {
restrict: 'A',
scope: {
toggleButton: '=checked'
},
link: function($scope, element, attrs) {
$scope.$watch('checked', function(newVal, oldVal) {
newVal ? element.addClass ('on') : element.removeClass('on');
});
element.bind('click', function() {
$scope.checked = !$scope.checked;
$scope.$apply();
});
}
};
};
angular.module('myApp')
.directive('toggleButton', directive );
}());