Extra 4: Custom Directive to Change Icon

Lab Length: 20 minutes


  • Change an icon based on the OS the application is running.

Key Concepts:

  • Using directives to change functionality

Table of Contents

1.0: Creating a Directive

There are many items in the Ionic Framework that change based on the OS of the mobile device. However the icons are not one of those items. In order to change the icons based on the platform, you need to create an Angular directive.

  1. In the www/js directory, create a file called StarterDirectives.js
  2. Paste the code below into

         angular.module('starter.directives', [])
         .directive('phoneicon', [function () {
             return {
                 restrict: 'E',
                 replace: true,
                 scope: false,
                 template: '<i class="icon"></i>',
                 compile: function (element, attrs) {                    
  3. Now that the directive is setup, you will need to modify the compile function to set the correct class on the template.
  4. Using the information gathered from http://ionicframework.com/docs/api/utility/ionic.Platform/, set the icons to the following:
    • Default Icon: ion-ios-telephone
    • Android Icon: ion-android-call
    • iOS Icon: ion-ios-telephone
    • Browser Icon: ion-ios-telephone
  5. After you have figured out the correct class name, you can set it in the compile function with the following code:


1.1: Using the Directive

  1. In order to use the directive, you need to add the directive javascript file to the index.html page
  2. Then you need to tell the angular module to inject the starter.directives module
  3. Finally, replace the phone icon in the contactdetails.html file with <phoneicon></phoneicon>
  4. View your application in the browser, http://localhost:8100/ionic-lab
    • iOS is on the left and Android is on the right


  5. You can do the same thing for the other icons if there are different icons that you want to use based on the platform.


With a simple directive you were able to change the UI to have different icons based on the platform. This is a very usefulto your end users so that they get the expected look and feel for their devices platform.

back to top 