Getting started with learning a Front End Framework – IONIC 3 for dummies

I’m pretty much starting my 2018 (the new year spirit!)  a little late, well, atleast for my blogging. Many aspiring web developers would have already gone through this awesome link, a developers roadmapwhich clearly shows what developers need to learn to sharpen their skills in this year (or for many). Also a good place to get started for newbies. For the next few weeks, I’ve chosen myself to sharpen my skills in at least in one Front End Framework and the one is IONIC 3. So, I’ll be writing this IONIC 3 for dummies tutorials which will slowly catch up from basic to advanced. We will also cover the things required for knowing IONIC 3.

But before learning a IONIC 3 framework, devs who hasn’t got experience from any UI Framework or devs who uses Framework without knowing its pros and cons (like myself), we are going through a short introduction for learning a UI Framework first.

Importance of Learning a Front End Framework!

Last couple of years are ruled with tons of frameworks, especially JavaScript Frameworks. I started out my job career in PHP, but then I shifted to JavaScript works couple of years ago since the popularity of JS is ruling upwards compared to PHP.

Of course its not right to compare PHP with JS, as JS is a front end application. But the point is, long back ago, before Angular 1, there wasn’t much hype about UI Frameworks, most UI tasks can just be accomplished using jQuery, views can be easily created using PHP Frameworks like CakePHP, Codeigniter, etc., itself. You can put whole logic in view using PHP itself (much simpler I say.) Life was fine!

But as time goes by, the idea of breaking the MVC chain to MVVM type came and along with the idea of making the application more of a service kind, a RESTful service. Because of tying a knot on view with application logic, it  not only slowed the down work, but, it’s not right itself! Why should a view should be generated by backend logic as HTML belongs to the Frontend?  Every request made to server will be regenerated into a HTML from PHP (like framework templates). This seemed wrong!

Another reason is, the birth of mobile application and support of websites in mobile devices became a huge deal due to smartphones like Android and iPhone. Of course, we can do those stuffs in PHP Frameworks, but, It will only make our code messy! So, Yea, another great idea of taking the view out of backends codes.

And Finally, creating a view resuable for multiple service is not possible using single service, since view is tied closely to the controller/service in MVC. If we could break down the view from the MVC logic, we can easily resuse it.

Pros of Front End Frameworks:

  • Easy plugin and play
  • Core codes are well tested and can get help from frameworks community!
  • Hides the complex parts and makes develop much fast
  • Overall, time will greatly reducing when developing something

Of Course, there are n numbers of reason of getting to know a Front End Frameworks, but, above are few of my points which made learn one or two frameworks in Front End.

Difficulties in Learning a Framework

As I was saying, there are tons of Front End framework and trying to learn every one of them is not even possible, also know that, before completing one Framework, it will be updated to new framework (yep!) which is totally different from what you have learnt (Ex. Angular 1 and 2).

I worked on a Angular 1 project long back ago, at the time Angular is so popular, but at the time of completion of my project using Angular 1, Angular 2 was released. The difficult part is migrating from Angular 1 to Angular 2. It was seriously so difficult and I have abandoned the idea of migrating and stuck with Angular 1. (Another reason is, I took lot of time working on Angular 1)

Cons of Front End Frameworks:

  • You have to spent lot of time learning a new framework (even though you know vanilla JS)
  • Have to learn any additional dependencies comes along!
  • Chances are, you won’t need lot of codes you get from the Framework for what you want to accomplish
  • You don’t control the core framework codes.

How to Decide On Choosing a Awesome Framework

Considering this Pros and Cons of using a Framework, its upto you to decide whether to use one or not, which depends on number of reasons.

  • Know what you want to accomplish – There are full MVC Frameworks like CakePHP and MVVC – AngularJS, Micro Frameworks like Slim Framework etc.
    • Once you understand what you need, you easily pick from the best out there.
    • For Ex: If use both AngularJS and CakePHP, view part from CakePHP will be completely unnecessary since it will be handled my Angular. Its best to choose a microframework.
  • Analysis the pros & cons of each frameworks. As we already know, we have megatons of frameworks out there,you have value each framework before picking one.
  • Know the future support of that Framework, you don’t want to end of using a abandon Framework!

IONIC 3 Framework – Starting an Awesome Framework!

Which framework is best is 2018, well there is Vue.js, React and Angular JS 5 ofcourse. But, there is also IONIC Framework.

Why IONIC Framework?

IONIC Framework provides an easy way to build hybrid mobile apps using Web technologies like CSS, HTML5. Its build on using AngularJS and underneath it uses Apache Cordova (Previously PhoneGap) in order to run as a native app. The sweet thing about IONIC which i love is the mix of different wonderful things it puts together

AngularJS is the most popular framework in Front End for long while and if you search for job opportunities in Front End Framework, It will be AngularJS in the top!


Next one is Apache Cordova, provides a easy way to build mobile applications. It turns your native HTML, CSS and JavaScript to Mobile supported format by providing a wrapper which acrosses all platform.

apache cordova

Third one is, Typescript – the whole IONIC 3 code needs to written in typescript. Typescript provides When your code base is huge, and more than one person works on the project, a type system can help you avoid a lot of common errors,  cool ES6 syntax and converts them just like Babel does and more. Though it might feel pain the beginning who doesn’t want to use anything except pure JavaScript. Besides, It will only be hard for a month or so, but the benefit using Type Script is a lot! (To know more about


And finally, NodeJS, IONIC 3 provides easy build system, livereload

Problem in Learning IONIC 3 Framework

So far the problems I’ve faced is the documentation.

Run a CLI, You gotta all the pages and download this and tada, you gotta cool like mobile form!

Well, It does good for people who just want to develop something without knowing what. But, sooner or later, you will need to now how it actually it works without too much automation which hides the step by step approach. It couldn’t find resource anywhere to have clear understanding of who things goes. Also, since IONIC depends on Angular and Type Script, lot of syntax explanation seems to skipped assuming people knows them. Well, actually I don’t.

Next Blog… Getting Started with IONIC 3 Framework

Most of this session seems very theory rather than code, I promise to be less theory as most of them don’t like it!:D

From next sessions onward, its going to be equal explanations and code. We will be learning some few

  1. ES6 functions like import, export, classes etc.
  2. Basic Type Script along the way.
  3. Then AngularJS @component commands. (We are not going to cover entire AngularJS, since tons of tutorials exists for that already) and
  4. Then a basic installation of IONIC 3. A Re-Introduction to IONIC 3 for beginners.



Learn JavaScript – 3 Cool Browser API’s You See Everyday (Which You Gotta Know)

Have you ever wondered how food delivery or call taxi sites/app gets your location from mobile? Browser notifies you that your facebook friend just liked your profile picture? Yep, these are all Browser API’s and they are becoming cooler and cooler by the minute and it’s kinda hard to catch up. There are lots of browser API’s here we are going to see about some of the most useful API’s along with examples.

3 Gotta Know Browser API’s

  1. Geolocation API
  2. Page Visibility API
  3. Web Notification API

1. Geolocation API

One of the coolest API is the Geolocation API

  • Users visiting your website/App location is the best way to track analytics.
  • Websites like shopping cart, delivery item, taxi can use this information to know the user physical location instead of asking them to provide address like the olden days.

How Geolocation API Works?

  • Using GPS and location information like IP address, Wireless connections, Cell tower information, Latitude and longitude are available in JavaScript.
  • Mobile phones usually works by first triangulating the user location with mobile network and use GPS to pinpoint the location for high accuracy

Steps to Get Latitude and Longitude

  • Privacy is a huge concern since we are actually trying to retrieve user location.
  • So, in order to obtain lat and long to use with JavaScript, the user has to first share his location

web apis

  • Once the user allows, you can easily fetch the lat and long from the below functions.

Once you fetched the coordinates successfully, its up to you decide how to use this information whether to show in maps or fetch address (Google maps can help with these)

Browser Compatability:

web apis location api


2. Page Visibility API

Have you wondered how a website playing a video pauses when user switches to different tab? Well, Page Visibility API does the trick. We can even use this concept to great extend our application functionality when user is not active by saving resource.

How to use?

Page Visibility API provides 2 methods to use it,

  • document.hidden – provides a boolean whether the page is hidden or not
  • document.visibilityState – using visibilitychange event, triggers when state of the page window changes

Using this simple concept, you can turn off any unwanted process in your UI when user is not active in the website.

Browser Compatability:

web apis page visibility api


  2. Cool example:

Web Notification API

Notifications are important in letting users know any information from the application

  • Whether to tell them they are idle for a while
  • or think of a simple chat whether needs to informed whether user pings them even when they are idle or in some other tab.
  • Reminding user to perform certain tasks like ToDo application.

The Web Notification API lets these notification from web application or app to send information.

web apis notification api



How to use Web Notification API

  • Similarly like Location API, first users has to allow permission to allow. Else, these can become another SPAM dump.
  • Once granted, you can send notification message easily.
  • It’s even possible to set close notification, add handlers etc.

web apis notification api

Browser Compatability:web apis notification api



Well, thats it for now. Still there are tons of Web APIs like Web Workers, MediaDevices.getUserMedia, Battery API etc., checkout in

The Bad and The Worse – JavaScript Scoping Issues

Hope you all gone through how amazing JavaScript worker is. Today, we learn something core to JavaScript. Every language has its bad sides or “How not to use/write code” like that. Lately, I wrote JavaScript more than 3 years now and felt I using it well. But, every time looks back and read see my code a couple of months back, it looked awful. Over the times, I kept on learning and improving thanks to my mentor and colleagues. I started using Linters and learned what are the ways to write and ways not. So this about the bad side of JavaScript and especially Javascript scoping issues, which is the pillar in understanding this language for proper use.

JavaScript Scoping Issues

To know the JavaScript scope issues, first, we have to understand about global variables how it works and what is the scope.

Understanding Global Variables

Global variables or variables belonging to window are the great aid to newbies, Just assign a value in a global it can be used anywhere. Its pretty helpful, but, you don’t how bad it is until you are code starts getting bigger and bigger till you end up not knowing where the variables it declared.

Take this simple code,

As you can see thisIsGlobal is declared outside the function which automatically becomes a global level variable, it can be used anywhere. Can anyone see the problem here?

In the function foo I’m just directly using a thisIsGlobal. If the function foo becomes big, you will have no idea where this variable come from.


This example shows the badest way to use a variable. The variable ‘poem’ becomes global, function getPoem becomes global. Based on the order of usage in index.html, they are overwritten.

Solving This:
Never use a variable outside the function or put a function directly in a file. Better way to do this wrapping it like this,

The Scope & JavaScript Scoping Issues

What is scope? It is nothing but,

A block of statements wrapped in a curly braces. The one we seen previously is called ‘Global Scope’. And there is, Local/Functional Scope and Block scope (Recent JavaScript version)

Okay, the bad stuff here, when compared to other languages like PHP, is, if you forgot to var inside the function getPoem, it will automatically become a global variable.

Solving This

Always use var keyword inside a function in the very first line it starts.
Avoid global usage even intentionally

And Block Scope
The let is something new, its only supported in few browsers which support block level scope

Hope it makes it clearer about how scoping works in JavaScript and how it won’t show any errors or warning. Understanding how scope works and its usage and flaws are must for any developers.


Understanding Web Workers

Before getting to Web Workers, let us understanding the purpose for its need and how JavaScript works.

everything is single“,

  1. JavaScript will execute everything in a single thread.
  2. Each statement is added to a stack and will execute one-by-one.

The good thing is, our code will execute in a synchronous way. But the bad side is, rest of the statement in the stack has to wait if the current process takes a lot of time.

Performing heavy ‘client to server side’ task or huge data processing like JSON or complex calculations which going to taking a lot of time.

Eventually when we run this code, either it might freeze and become unresponsive or ends by blocking rest of the process (or both).


To solve this problem, we are going to use something called ‘Web Workers‘, which runs independently of any user interface. All the statements/code mentioned in ‘Web workers‘ will run in the background. Well, let’s get started.

  1. Need for Web Worker!
  2. What is Web Worker
  3. How it works
    • Creating a Worker
    • Web Worker Communication
    • Importing External Files
  4. Web Workers Example
  5. Stopping a Web Workers
  6. Handling Errors
  7. Security Concerns
  8. How to use & When to use
  9. Browser Compatibility

Consider the following example,

Not only it will take a lot of time to print the statement ‘end’… our browser freeze and hangs and you might end up killing the process.
Let’s see how the above code runs in Web Worker. To create a worker


Now, if you run this you won’t see any freezes at all! That’s the magic of the Web Worker.

So, What is Web Worker?

Web Worker provides a way to run the task in the background and independently of any user interface. We can put any long running tasks in workers which will not interrupt keyboard or mouse click events.

  • It enables to offload expensive operations
  • It includes separate message queue, event loop, and memory.

How it works

Creating Worker

Web Worker are created using the object Worker()

The new Worker('javascript_file.js') will look for a file named ‘javascript_file.js’ which will run independent thread from our actual code.

Web Worker Communication

To communicate to and fro from our worker we’ll use window.postMessage to pass messages.

Import External Files

Using importScripts you can import JavaScript files inside workers.

Let’s see an example, to understand all this stuff.

Web Workers example – Creating a simple Web Worker to poll for contents.

In this example, we will randomly fetch contents from Wikipedia periodically from workers in a nonblocking way.

First, let’s build the worker part and then create our index.html to link the worker. See the code below for explanation

Stopping Web Workers

Once our Web Worker is created, it will continue to listen for any changes using the event listeners, when it’s time to stop use the terminate command.

Handling Errors

The onerror event listeners we will attach the Web Workers for capturing any errors.

or simply

Security Concerns

Since Web workers use postMessage for communication, the origin needs to be checked on receiving the message.

Web Workers Limitations

Though awesome it seems there are some limitations with Web Workers.

  • You cannot access the DOM from web workers (I.e, No document, getElementById)
  • Cannot access global objects or functions on the main page
  • Workers have high start-up performance cost and high per-instance memory cost. So it’s best to use minimal amount of Web Workers
  • Communication to our application only be carried our using postMessage

Overall Web Worker is must use any high processing tasks, from web polling high data processing, it does’em all. But, know when to use Web worker and when not to. You don’t need to use it all the time. And finally, there are other types of Workers which will see it soon.




Keeping Promises using JavaScript – Part 1

Promises using JavaScript is not something new, it has been introduced years back, but we are not using because of not all the browsers didn’t support Promises at the time.

Before using Promises one should have clear idea about why need to use promises, as there any alternate apporaches to it etc. I seen lot of blog just giving a example to get started on promises before even explaning about basic asynchronous concept or even callbacks, which are related to JavaScript Promises. Below we are going to cover almost all concept involving around promises.

Life in Synchronous & Asynchronous Way!

Synchronous are things which are aligned over time, i.e one has response to the other and so on. For example, conversation is synchronous, dancing like that.

JavaScript, by default holds to things and do it one by one which we id this a “synchronous” (Except for few things like AJAX calls). Because JavaScript is single threaded and code will run one after an another.

Eventhough the working of ‘Synchronous’ can be useful for debugging; but it limits the thought of doing things multiple.

The problem with handling multiple things at the same time is “how to handle” the response? However, there are lot of other options to try.

Living with Callbacks!

Callbacks are nice way to acheive “asynchronous” way! Just a create a function, wrap the environment and pass it on, so it can be triggered somewhere else.

Example: simple callback

This is just a simple example, we can create even more complex callbacks. But there comes a problem with callbacks which are difficult to solve.

Example: Deep nesting A.K.A callback hell

{ function OnSuccess() { function DoThat() { …. } } function OnFailure() { function CallThis() { } } }

– Deep nesting
– Inconsistent callback behaviour
– Handling Errors
– Chaining

you read more about issues on callback from []

What about Events?

Similary like callback, events are great way to attach multiple times on a same object. Managing success and failure is still tricky!

Writing as Human Brain’s – Promises!

Promises – an asynchronous operation which provides great way to handle simulationous requests with precesion. They provide callbacks like functionality for each indiviual requests with more control both success and error data.

Promises exist to represent something that will be available in the future

Promises are very Promising because…

  • Code looks clean and more readable
  • Catching errors
  • Chaining
  • Multiple API calls &checking it simultaneously.

Solving the callback hell using Promises!

even better, chaining,

also, simultaneously run!

With JavaScript Promises, you can acheive the asynchorous way with ease and have more control over the data. In the part 2, we will some examples in action and also we need to know when to use Promises and when not to use it. Thats it for today! Enjoy!

Promises ain’t Callbacks; Its better!

  3. (for the image)

Geolocation API — How to get current user location

Before using Geolocation API, lets understand why need to use it.

If you are building a web application, there will come a time where your need to know the current location of the users. Why I need to know the location of the users? Because you might need to show contents relevant to the location of the user or even change your locale based on it or even you can allow use to track location using app ex. fitness apps.

Geolocation API

JavaScript has an API which can be used to retrieve the user location, only if user allows permission. Below is a script simple script to do that!

Breakup of above Geolocation API

1) Getting Geolocation object

We check for whether geolocation api is currently supported in our browser.

2) Getting Current Position

Now if the thing is supported, we can easily pull the latitude and longitude of the current user location.

Make sure to provide permission for browser to pull your current location

Geolocation allowing permission

 3) Watch Position for Change.

Finally, you can use the watch to track the changes in user location and update it. (cases in which we provide mobile apps like fitness app to track user jogging locations)

4) Using Google Maps or OpenStreepMap to display the fetch information in a awesome map

Google Maps:

OpenStreeMaps: (Make sure to include OpenLayers.js)

You can even revoke permission later to any site by clicking the label in address bar.

Geolocation revoking permission

Geolocation Accuracy

Geolocation is most accurate for devices with GPS.

“W3C Geolocation” — the Web site will get the accuracy of whatever geolocation method (whether based on IP, access point MAC, GPS, cell-ID, etc.)

Some Web browsers have access to GPS receivers. Some of them (like Firefox and Chrome/Chromium) can use the MAC address of a WiFi access point to query Google’s database of the locations of WiFi access points.

Geolocation API removed from unsecured origins in Chrome 50

 According to Google API,
It is an important issue as it will directly impact any site that requires use of the geolocation API and is not served over https, but it is a change that we do believe is beneficial to all users on the web. This post should help you understand the reasoning and how to proceed.

 Browser Support

geolocation browser support
geolocation browser support




Yet another UI Framework — Aurelia For beginners

AngularJS is one of the coolest front end frameworks I’ve ever used, but it doesn’t hurt to try more Frameworks. One Em is Aurelia, a actually simple JavaScript framework or say framework of tomorrow. (Just like AngularJS). Below aurelia for beginners provides an insight of how to install and also know the difference between AngularJS and Aurelia.

Getting started with Aurelia for Beginners

Why aurelia is awesome? Because of the few below stuffs which makes it easier to run and understand at the same time, it still gives the power to write very simple code. So, anyone can easily write a Aurelia code.

  1. Focus on business logic, not on framework
  2. For users looking for fast development also providing a structured UI FRAMEWORK
  3. Written with next-generation EcmaScript. Integrates with Web Components.
  4. Similar to AngularJS, “Two-way” Binding
  5. Can be written using ES5, ES 2015, ES 2016 and TypeScript


There are lots of way to install Aurelia, you can use Yeoman, Webpack or simple Aurelia-CLI


  1. NodeJS 4.x
  2. npm 3
  3. npm aurelia-cli

To make it less dependent on machine installation (Ubuntu/Windows), lets install aurelia in Docker. So, it can run in any machine! Cool!!

Installing Aurelia on Docker for Windows

1. Create a Dockerfile with below content

2. Now run docker build -t aurelia/cli

3. Now you have the Docker image lets create a container for this image and bash into it!

4. After executing this command, you will be inside the container. lets check whether it is installed correctly with the $ aurelia

checking aurelia in windows
checking aurelia in windows

Starting your project

Using the in-built Aurelia CLI command lets create a project. (Since you previously ran docker run command, you’ll be inside the container now)

  1. Now cd /Aurelia
  2. Run the command to create a new project au new --here
  3. The wizard you can keep hitting enter (unless you want to modify the default value. I’ve choose Sublime Text editor instead of VS Code)
  4. Now see the project directory, it’be created.

    5. Finally after confirmation you have created a project successfully (with everything you needed for awesome in a jiffy)

Aurelia Vs. Angularjs

Now we’ve created a project, you can simple create a todo example and try it (skipping the setup part)

1. Syntax: No weird symbols or abstract naming, just similar syntax to what you can already find within Javascript itself.

2. ES6 Support: You write web applications using ES6 syntax and not have to worry about ES5 support because the included build system and configuration. With AngularJS, you’ve to learn its abstractions; directives, controllers, services, factories

3. Pluggable & Modular: Framework that can be decoupled to the point where you can use parts of Aurelia in other applications/Node.js modules.

4. Templating in Aurelia: Utilises the W3C HTML Imports specification for importing HTML templates and logic.

5. Dependency Injection: Just define a static method that returns what you want to be injected into the application!

Overall Aurelia seems and better than AngularJs in terms of simplicity with power matching to AngularJS. But, there is one question goes in the mind of most of the UI Developers, why another UI Framework? We just learnt and starting using AngularJS and now another?

Well, Aurelia is created long back and thing is that, there is always going to be tons of ‘yet another framework’ whether is PHP or UI or whatever, you can either stick to what you like or learn something new. And there are so many “new”, so might good and provide tons of new features and browser support or some might now. So before trying a new Framework your application, it’s better know the ups and downs of a framework and its support. Both Aurelia and AngularJS are great frontend framework! But, comparatively with Aurelia, AngularJS is very well know and has tons of support over the web.

Well, thats it. Thank you for reading!



AngularJs Tutorial 8 — Simple Notification Directive Using Event Dispatcher

Now this is fast, my second article in a day. I guess its the only way to stop thinking about ‘She-Who-Must-Not-Be-Named’. Well coming to matter at hand, I worked in AngularJs for a while and always missed a good notification thingy. Twitter Bootstrap notification seems good, but, so static like a zombie. So, finally thought of creating one angularjs tutorial! A simple angularjs notification plugin/component.

Also, we are going to learn something new along the way

Event Dispatcher!!! (Taa-daa!)

Wait a minute, AngularJS has “Event Dispatcher“?? Yep! They do… and they are done using “Angular $emit“, “Angular $broadcast” and “Angular $on

Ok, before going deep, why the hell should i use “Event Dispatcher” if i could do a simple inheritance like function call?!!

Answer: Some actions or asynchronous activity should be handled in a way which shouldn’t alter the existing application flow. Like in our case, even if notification doesn’t work, its a not big deal, but, it shouldn’t interrupt our actual application flow.

And geeks used to call this as Observer pattern.

Some other good examples are ‘logging’.

Generally, an Event has ‘Publisher’ and ‘Subscriber’. In our case,

  • Publisher – $emit & $broadcast. The difference between both of’em are
    • $emit – dispatches the event upwards through the scope hierarchy.
    • $broadcast – dispatches the event downwards to all child scopes,
  • Subsciber – $on

Now, for our example we need existing cool notification library and Noty ( is one of the few best notification plugin library available. (simple and… cool)


Checkout ->

1) jade/index.jade

2) coffee/directives/

3) coffee/controllers/

4) coffee/

As you can see:

(1) Like before we created a directive, with 4 params. 

  • Always remember the rules, the only way to send a message to a directive must be through ‘isolated scope’ else, its not a reusable component. Each should independent!

(2) Our ‘notifcationDirective’. Pretty understandable!

(Note: Here we added a “$watch” on ‘uuid’. Because, we need to know whether the data outside our directive gets changed or not. Suppose, if we watch on ‘message’ and message is same for the second trigger also, $watch thinks as the previous one. So, we are watching something which changes on every action trigger.)

(3) Our Event Publisher, its Publishes data when button gets triggered

  • $scope.$emit('notifyEvent', notifyData)  – eventName and eventData (2 params)

(Note: Here we are just manually triggering sending the data. We can easily changed to how we need)

(4) Our Event Subscriber, Receives the data whenever a publisher pushes the data

  • $scope.$on(‘notifyEvent’, (event, data) 
  • From here, we are pushing the data to our jade/index.jade where our directive is located.

Thats it!! Now, try clicking all the actions….. pretty cool, huh! (Check their plugin for more options to meddle with)

(I know, screenshot is worse xD)

Thats it for now!!! An event handling in AngularJs is so very easy peasy.

Check it out —>



AngularJs Tutorial 7 — Creating a Simple Component using Directives (with a Charts example)

Its been a while. (seriously!), its like getting awake from incubation chamber and write another angularjs tutorial!!

And, today we gonna see AngularJs Directives.

Why should i use Directives?!

  • Reusable components!
  • NEVER manipulate DOM from your Angular controller/anywhere except via directive

They are…  “A powerful tool for modifying the DOM”. As we know, AngularJs does the compilation stuffs of DOM and any other event related to it and if we directly add some event (like we do using jQuery) is seriously wrong. We surely end up messing AngularJs.

To handle this, Angular Js Directive provides a methods such $compile, and whatever we mention their will get compiled by AngularJs itself.

AngularJs Compilation Cycle:

Compile function:

  • Used for template DOM manipulation ,
  • Provided by directive, (Hence manipulations that apply to all DOM clones of the template associated with the directive.
  • Ex: Manipulation of tElement = template element)

Link function:

  • Used for registering DOM listeners and as well as updating the DOM.
  • It is executed after the template has been cloned — e.g., inside an <li ng-repeat…>, the link function is executed after the <li> template (tElement) has been cloned (into an iElement) for that particular <li> element.
  • Ex: $watch expressions on the scope, manipulation of iElement = individual instance element

Now, getting back to our example, but  before that I’m not gonna start teaching from “Hello directive”. Eventhough AngularJs documentation sucks, go through it anyway, we will get a basic idea.

Now, lets see the AngularJs directive using ChartJs

And here is the Repo :

1) jade/views/charts/index.jade

2) coffee/ 

3) coffee/directives/

As you can see:

(1) We just created a directive element called trackr-piechart using an Element.

(Note: You can even create element like <div trackr-piechart=''></div>, but, as conventation to be followed according to AngularJs,

  • Use an element when you are creating a component that is in control of the template.
  • Use an attribute when you are decorating an existing element with new functionality.
  • Also, make sure to keep a ‘prefix’ for your directive element, (if in case, may be in future HTML 8 or 9 and there already existing an element ‘<piechar..’> might clash with ours. so go with prefix! 🙂


And, we have passed ‘title’ and ‘data’ to the directive

(2) Injection and defining our chart module

(3) In Piechart directive, we have used

  • @chartModule – using the chart module we have created to make a directive (watch the naming convention of the directive with the element, it matters!)
  • scope – Making it isolated scope. so can can use many ‘piechart’ individual components multiple times in a page.
  • restrict – Restricting only to ‘E’ means element.
  • templateUrl – We are keeping the template separate, though you can keep it here itself. Might look ugly if the template starts to grow
  • link – Whatever mentioning here will be added to the link cycle of AngularJs

Thats it. Add some data in our controller and which it make a beautiful piechart. Easy peasy!!!

(Experiment: copy and paste many <trackr-piechart> and provide different data they will work independently thats how a component should be!!! (Thank the isolated scope)

Now, the disadvantage of isolated scope is, you cannot directly tie the controller to our chart directive.

(4) coffee/directives/

For this, checkout our second linechart example

Setting ng-model

As you can use, we tie the input title to the directive template and added a $watch in our directive to know anything changes. Thats it!!!

Check it out —>



AngularJs Tutorial 6 — Pt 3 — Building a RESTful Application With PHP & MongoDB

I guess all the people are same, inside. All they want is fun and when commitments comes by, they say ‘Ta-Ta’!!!. God, when are they gonna learn “You have to fight for something u believe in and nothing can be obtained without sacrificing certain things’….But, I have no regrets, I gave everything, but, you will have.

“If you love somebody, let them go. If they return, they were always yours. If they don’t, they never were.”

Anyway, back to topic.

Our final tutorial in building a Restful API – AngularJs & PHP (with MongoDB) is Complete!!!

So, What are the things we gonna see…

  • [API] – CORS!!!
  • [UI] – Advanced concepts in AngularJs $resource & Custom reusable resourceFactory

CORS – “cross-origin resource sharing”

It means “Cross-Origin Resource Sharing (CORS) is a specification that enables truly open access across domain-boundaries.

To explain it simple, “Generally, One(web) cannot access or request or send resource to another domain, unless both present in same site(According to “Same Origin Policy“!). What CORS does is, it provides a way for cross domain access by specifying certain things in ‘header’ request, thereby allowing a site from another server can access!”


In our example, our PHP application runs in default ’80’ port. However, our AngularJS UI is executed via Yeamon-GruntJS, which is in 3501 port. So, when runned in browser, both act like in different server and our poor AngularJs cannot access our PHP/API part. 🙁

But, not to worry, Here comes CORS!!!


As you can see, all our response in our API are send to this ‘responseHandler’ method where we have specified our CORS.

Check here for detailed information about it


Note: Normally, to enable CORS, you first have to send a ‘pre-request or pre-flight request’ from UI (before making the actual request). That is an “OPTIONS” (similarly to GET, POST…).

But, AngularJS is nice enough to send it automatically, so you don’t have to worry about it when using $resource.

Advanced concepts in AngularJs $resource

“AngularJS Promise variables – $then & $resolved”

Before jumping into this, some have no idea what this is.

In our blogs application, we are making a request to fetch all ‘blogs’ from API and display in a nice tabular form.

Our code is something like this,

The second line makes an ajax call to API, and the result is binded to ‘$scope.blogs’ as expected. But, JavaScript goes in ‘asynchronous’ way, what happens is, before getting the result, our third line will be executed, which causes ‘undefined’ thingy!!!

To solve this, we need to make certain things in our code, ‘synchronous’, i.e We need to bind our ‘$scope.blogs’ only when we get response from ‘blogResource’. This is where AngularJs ‘$then & $resolved” comes in.

For updated code looks like this,

‘$then’ from AngularJs will be executed only when response comes in. Thus making our two-binding works nicely.

(Note: Older version of AngularJs $resource will not send $then)

And our lastly, our Reusable ‘resource factory’

This is a separate AngularJs factory which we used along with the controller showed before. We can use this simple usable resource methods for all of our new modules, say ‘Users’ or ‘Categories’ or ‘whatever’. Just inject in our controller, thats all. You can easily make a any kind of calls to our API.

(Note: PUT request is not directly available by AngularJs $resource, so, you noticed the difference in our code)

Thats it for our Simple Restful tutorial!!! Even though my explanation seems lil big, just browse the code to know how simple this is :). Just small bunch of files which creates an entire CRUD application.

What we have so far done is just a start, we will slowly continue to evolve… to next level. So, be sure to be with me 🙂

(And don’t forget to share :P)