Merry XMAS! Here is a very simple example of everything I talk about in my AngularJS directives article. Here you have everything in action: double bindings, transclusion, element replacement. And watch how small it is.
angular.module('ng').directive('toggleButton', function($filter) { return { restrict: 'A', replace: true, transclude: true, require: 'ngModel', scope: {'ngModel': '='}, template: '<button type="button" class="btn ng-class:{\'btn-primary\':ngModel, \'btn-default\':!ngModel}" data-toggle="button" ng-click="ngModel = !ngModel" ng-transclude></button>' }; });
To use this directive go like this:
<button ng-model="sideBySide" toggle-button >Side-by-side</button>
So all this directive does is replaces the element with a longer fully loaded and wired-up button found in the template. The class-switching as well as the click logic is done for you. This directive, in a way, works like a macro in C++. It allows you to write less and produce m0re. I wish the same could be said about making babies.
Note that we have replace:true in the directive, so it makes no difference whether you are calling toggle-button from a <button> or <span> or anything else for that matter. However for readability, I prefer to still use the <button> element. Also note the transclusion is in effect here, so the text “Side-by-side” will be transferred inside our wired-up template button. Horray!
Also note that “bootstrap toggle button” implies you must have bootstrap CSS (version 3 or something) in order to have the btn-primary and btn-default classes. So don’t forget it! Of course if you wish the button to glow in red when active, feel free to change btn-primary to btn-error or write your own.
The post AngularJS bootstrap toggle button appeared first on Coding Insight.