Checkbox Alternative for Twitter Bootstrap

I have been working on many web applications for quite sometime.  I, as pretty much everyone else, want their sites to be usable on mobile devices.  One control that is not good on mobile devices is a chekbox control.  Hence, many mobile platforms such as iOS and Windows Phone / WindowsWIndows Store Apps prefer the use of switch control control instead:

image

I am also currently using Twitter Bootstrap, so I wanted to find a compatible control.  I found this project on GitHub – http://www.bootstrap-switch.org/ or https://github.com/nostalgiaz/bootstrap-switch/.  I wanted to give these guys props for developing an excellent product.  In my case, I wanted to use it in an Angular application.  Angular wants developers to create directives to manipulate HTML, as this switch control does.  So, I wrote a quick directive that wraps the switch code.

angular.module("bootstrap-switch-angular", [])
    .directive("bootstrapSwitchAngular", [function () {
        var switchDirective = function () {
            

            this.restrict = "A";
            this.require = ['?ngModel'];
            this.link = function (scope, element, attributes, controller) {

                if (controller) {
                    var isValueBeingSet = false;
                    var currentController = controller[0];
                    element.bootstrapSwitch();

                    element.on("switch-change", function (e, data) {
                        if (!isValueBeingSet) {
                            currentController.$setViewValue(data.value);
                            if (!scope.$$phase) {
                                scope.$apply();
                            }
                        }
                    });

                    var validator = function (value) {
                        isValueBeingSet = true;
                        element.bootstrapSwitch("setState", value);
                        isValueBeingSet = false;
                    };

                    currentController.$formatters.push(validator);
                }
            };

        };


        return new switchDirective();
    }
    ]);

I also added this to the fork of the project on GitHub.

Enjoy.

 

<musings>

I think some developers use open source projects without giving a second thought to who wrote them and how.  There are many, many open source project owners who spend their personal time working on these projects.  I do the same thing, as I have a few open source projects on my own on CodePlex.  I try to pause when I use fruits or someone else’s of hard labor and say ‘thanks’.  At the same time, if I can contribute something I do that as well.  So, give props to folks who help you in your endeavors, good developers, as I do now to the owners of Bootsrtap Switch project.

</musings>

2 Comments

Leave a Reply to Denis Konchekov Cancel reply

Your email address will not be published. Required fields are marked *