Sachin Siwach Sachin Siwach - 3 months ago 165
AngularJS Question

How to set text on md-Switch?

I am trying to set informational text on md-switch that comes under material angular design so that user can know what is the current state of a field value. Pictorial representation of what I want can beText on md-switch

How is this done folks? I am new to material design.

Answer

You could try something like this to add a label to md-bar using CSS:

md-switch.inline-label .md-bar::before {
  position: absolute;
  font-size: 9px;
  line-height: 13px;

  content: "off";
  right: 0;
  padding-right: 3px;      
}

md-switch.inline-label.md-checked .md-bar::before {
  content: "on";
  left: 0;
  padding-left: 3px;
}

Apply the class inline-label to your md-switch:

<md-switch class="inline-label" ng-model="data.cb1" aria-label="Switch 1">
  Switch 1: {{ data.cb1 }}
</md-switch>

angular.module('MyApp', ['ngMaterial'])
  .controller('SwitchDemoCtrl', function($scope) {
    $scope.data = {
      cb1: true,
      cb4: true,
      cb5: false
    };

    $scope.message = 'false';

    $scope.onChange = function(cbState) {
      $scope.message = cbState;
    };
  });
.switchdemoBasicUsage .inset {
  padding-left: 25px;
  padding-top: 25px;
}
md-switch.wlabel .md-bar::before {
  content: "off";
  position: absolute;
  right: 0;
  font-size: 9px;
  line-height: 13px;
  padding-right: 3px;
}
md-switch.wlabel.md-checked .md-bar::before {
  content: "on";
  left: 0;
  padding-left: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-animate.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular-aria.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angular_material/1.0.3/angular-material.min.js"></script>
<link href="https://ajax.googleapis.com/ajax/libs/angular_material/1.0.3/angular-material.min.css" rel="stylesheet" />

<div class="inset switchdemoBasicUsage" ng-controller="SwitchDemoCtrl" ng-cloak="" ng-app="MyApp">
  <md-switch class="wlabel" ng-model="data.cb1" aria-label="Switch 1">
    Switch 1: {{ data.cb1 }}
  </md-switch>

  <md-switch ng-model="data.cb2" aria-label="Switch 2" ng-true-value="'yup'" ng-false-value="'nope'" class="md-warn">
    Switch 2 (md-warn): {{ data.cb2 }}
  </md-switch>

  <md-switch ng-disabled="true" aria-label="Disabled switch" ng-model="disabledModel">
    Switch (Disabled)
  </md-switch>

  <md-switch ng-disabled="true" aria-label="Disabled active switch" ng-model="data.cb4">
    Switch (Disabled, Active)
  </md-switch>

  <md-switch class="md-primary" md-no-ink="" aria-label="Switch No Ink" ng-model="data.cb5">
    Switch (md-primary): No Ink
  </md-switch>

  <md-switch ng-model="data.cb6" aria-label="Switch 6" ng-change="onChange(data.cb6)">
    Switch 6 message: {{ message }}
  </md-switch>
</div>