65.9K
CodeProject is changing. Read more.
Home

Create an ON/OFF switch using Angular JS and FontAwesome

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.82/5 (5 votes)

Dec 19, 2014

CPOL
viewsIcon

58846

This tip shows how you can create a very simple on/off switch using Angular js and fontawesome.

Introduction

On/Off switch is a very common usecase in any admin interface or otherwise.Traditionally, we have used the many different jQuery plugins available for this purpose. When using AngularJs, we try and do everything the "Angular Way".

Though there are many directives already written for this purpose, I still preferred to create my own which believe me is super easy to make and later customize if need be.

FontAwesome

For those who aren't aware of FontAwesome, it gives you scalable vector icons that can instantly be customized — size, color, drop shadow, and anything that can be done with the power of CSS. Visit its github page to know more.

Let's Get Started

Assuming you have imported Angular Js and FontAwesome in your HTML, below is how my controller looks like:

Controller

angular.module('switchdemo', []).controller('DemoController', function($scope){
  
  $scope.init = function(){
    $scope.status = true;
  }
  
  $scope.changeStatus = function(){
    $scope.status = !$scope.status;
  }
  
})

HTML

body ng-app="switchdemo">
  <h1>On Off switch using Angular JS</h1>
  <div ng-controller="DemoController" ng-init="init()">
    <div class="well">
      <i class="fa fa-toggle-on active"
         ng-if="status == true" 
         ng-click="changeStatus();">
      </i>
      <i class="fa fa-toggle-on fa-rotate-180 inactive"
         ng-if="status == false"
         ng-click="changeStatus();">
      </i>
    </div>
    <pre>{{ status }}</pre>
  </div>
</body>

CSS

.active, .inactive {font-size:40px;cursor:pointer;}
.active, .inactive {font-size:40px;cursor:pointer;}
i.active { color: #5cb85c}
i.inactive {color: #d9534f}

Here is how this should look like once you are done...

Demo

I have created a demo on plunkr with this code, here is the link to it: http://plnkr.co/edit/Kc8M3enHJB7iwFRyGUDr?p=preview