Search code examples
angularjsangularjs-material

Best way to implement a toggle button in AngularJS Material


I am looking for a simple solution to implement a toggle button with a custom selected / unselected icon in AngularJS Material.

The functionality should be identical to the md-checkbox (with ng-model for the selection state), but I want to have my own icon displayed for selected / unselected state. md-checkbox does not seem to support custom icons, and md-button lacks the ng-model.

Preferably I would like to avoid implementing a custom directive and only make this work through css. Is this possible with AngularJS Material?


Solution

  • You can define a toggle function to create toggle activity in your controller, like this:

    $scope.toggle = function() {
        $scope.variable = !$scope.variable
        console.log($scope.variable);
    }
    

    Button on the html:

    <md-button 
        ng-click="toggle()"
        ng-class="{'active': variable, 'disable': !variable}">