AngularJS! One of the most popular javascript frameworks available today. Angular is widely used, be it an Intermediate web developer or enterprises like IBM, Paypal, Google etc everyone is using it. In fact AngularJS is maintained and supported by Google.

Due to its huge popularity, everyone wants to learn AngularJS but it has a steep learning curve because of its concepts like dependency injection, modules, controllers, services, models, 2-way data bindings etc which sound very hard and new for beginners.

It is so confusing because of too many technical words used in AngularJS documentation and also in many tutorials which are found online. So I’m writing this post for all beginners who wants a simple tutorial with simple words which can help them get started with the mighty AngularJS.

Prerequisites

Basic HTML & Javascript knowledge would be enough to understand this tutorial.

I love to learn by doing so I’ll be sharing examples along with code through out this tutorial.

Lets go!

Wait! but many beginners don’t know what exactly AngularJS does and where is it used in real life? – AngularJS helps in building web apps faster (web apps are nothing but web pages with added functionality and user interaction). By the end of this tutorial you will understand how it makes building apps faster and practical situations where AngularJS is used.

Getting started with AngularJS

Let me explain few concepts of Angular in simple words and then we’ll dive into actually using Angular.

Modules

A Module is just a container of some Javascript code. Modules are used mainly to organize your Javascript code. Every angular app should have at least one module.

Example : If you are building a webapp like facebook then you can organize your Javascript by having code for profile in ‘Profile’ module, code for newsfeed in ‘NewsFeed’ module etc.

Controller

A controller is just a sub container with additional functionalities.

Example (building a webapp like facebook) : Javascript code for liking, commenting, sharing posts on newsfeed would be placed in ‘PostController’ and code for displaying ads would be placed in ‘AdsController’

$scope is an important object in a controller. $scope is the object which contains all the data of a controller. Each controller has its own scope, data in scope is available only to that particular controller. So ‘PostController’ cannot access scope of ‘AdsController’

Dependencies

dependencies are objects which are required by a controller, we specify all the dependencies required when creating a controller.

Example : to use $scope in a controller, we specify it as dependency and then use it in controller. This concept would be clear once we start creating a controller in next few steps.

Directives

A directive is like an add-on for HTML elements. directives provide additional functionality to your HTML elements. There are many Angular directives and each directive has a different use. We’ll be talking about few directives later in this tutorial.

Putting the pieces together

Now that we know few basics of AngularJS lets dive into creating an angular app!

I’m using codepen.io to write HTML,CSS,JS and see the result live in browser. you can start writing code along with this tutorial as the steps are being explained. go to codepen.io, create a new pen and use this basic html below and then follow next steps.

<html> <head> <meta charset="UTF-8" /> <title>My first angular app</title> </head> <body> <div>Hello World!</div> </body> </html>

Steps involved in creating an Angular app :

1. Add AngularJS to your HTML page using script tag

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.9/angular.min.js"></script>

2. Create a module

syntax for creating a module :

angular.module(‘modulename’,[]);

lets create a module and assign it to a variable

var myApp = angular.module('myApp',[]);

3. Create a controller

syntax for creating a controller :

Module.controller(‘controllername’,[dependencies,function(dependency variables){ }]);

lets create a controller and also use $scope object to store some data lets say app name. we need $scope object so it should be specified as a dependency.

myApp.controller('MainController', ['$scope',function($scope){ $scope.appname = "Awesome app"; }]);

4. Start angular

we can start AngularJS by specifying the main module using ng-app directive in <html> tag of your HTML file.

syntax for ng-app directive :

<html ng-app="modulename">

Name of module we created is ‘myApp’ so we specify myApp as main module :

<html ng-app="myApp">

Also lets add controller to body element using ng-controller directive. ng-controller directive lets a html element access the data in that controller. we are adding contoller to body element so whole body has access to controller’s data.

<body ng-controller="MainController">

These are the basic steps to create an angular app. Now lets use some data to test if AngularJS is working.

We have defined appname varibale in scope of main controller, To access scope data in html angularjs has a special markup! requried variable has to be wrapped with in ‘{{‘ and ‘}}’ To access appname variable we can use {{appname}}

Add a <p> tag with welcome to {{appname}} as below and result should be welcome to Awesome app

<p>welcome to {{appname}}</p>

If something went wrong then cross check with code below :

See the Pen How to create basic angular app by Ranjith (@Ranjithkumar10) on CodePen.0

Diving deeper into Angular

Let get into few more concepts like 2 way data binding,filters along with few commonly used directives.

2-way data binding

In simple words, angular allows us to change data both in html and javascript. Also change in one place is reflected in another place.

Refer example below.



See the Pen AngularJS 2-way data binding by Ranjith (@Ranjithkumar10) on CodePen.0

If you type your name in the textbox, it instantly updates your name in the next div! Have a look at html.

ng-model directive is used to bind value of a textbox,radio button,select dropdown etc.

I used ng-model directive to bind the value of text box to variable named “yourname” and then used the same variable in next div using angular markup {{yourname}}

whats happening here?

When you type name, angular updates ‘yourname’ variable, ‘yourname’ variable is changed so the div which uses ‘yourname’ variable also changes!

If you change ‘yourname’ variable in javascript, textbox value and div text also will be changed! This is 2 way data binding. we can change data in both html(view) and javascript(model), one change will be automatically reflected in another. we need not write code for updating data, we just tell angular which element depends on which data and angular does all the work for you!

ng-repeat directive

ng-repeat, The most useful directive in angularJS. This directive is used when there is data which need repetitive HTML elements. ng-repeat can be used with any html element, syntax is as follows :

<div ng-repeat="item in array"></div>

example : $scope.friendslist = [“name1″,”name2″,”name3″,”name4”] then display friends in html using :

<ul><li ng-repeat="friend in friendslist">{{friend}}</li></ul>

check result below



See the Pen ng-repeat example by Ranjith (@Ranjithkumar10) on CodePen.0

Filters

Filters in AngularJS are used to format data. some useful filters are as follows :

currency : formats a number to currency format date : formats a date to specific format lowercase : formats a string to lower case uppercase : formats a string to upper case json : formats an object to json string

syntax is as follows :

<div>{{mydata | currency}}</div> <div>{{mydata | date:'yyyy-MM-dd'}}</div>

ngRoute module :

AngularJS is a powerful framework which can also control routes and views of an app. you can have multiple routes and assign views to routes using ngRoute module.

example : if your app URL is http://myapp.com/ then routes would be http://myapp.com/home, http://myapp.com/profile and content in these routes can also be managed using ngRoute module.

usage :

first add ngRoute using script tag (ngRoute is a separate module from angularJS version 1.1.6)

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular-route.min.js"></script>

add ngRoute module as dependency to main module

var myApp = angular.module('myApp',['ngRoute']);

configure routes using config function by adding $routeProvider and $locationProvider as dependencies

myApp.config(['$routeProvider', '$locationProvider', function($routeProvider,$locationProvider){ $routeProvider .when('/home', { templateUrl: 'home.html' }) .when('/profile', { templateUrl: 'profile.html' }) .when('/settings', { templateUrl: 'settings.html' }); $routeProvider.otherwise( { redirectTo: '/home' }); $locationProvider.html5Mode(true); }]);

add ng-view directive

<div ng-view><div>

In the code above, when URL is myapp.com/home then content from home.html is injected into div with ng-view directive. same with profile and settings, if route is other than specified routes in config function then redirected to /home.

home.html, profile.html,settings.html can be uploaded as separate html files, they can also be used as inline templates which is very useful for a single page app and explained in next section of this tutorial.

Lets develop a Movie DVD store app using angularJS to apply all the concepts learned in this tutorial.







The fun part – Developing a Movie DVD store app

We are going to develop an app which shows a list of movie DVDs, prices of DVDs for purchase and rent. user can select preferred DVD then moves to a confirmation page then a checkout page for payment and finally a thankyou page for showing successful transaction.

List of movie names, image URL, price, storyline are stored in a json file for this app. usually apps have a backend storage where all data is stored in a database.

As this tutorial is all about AngularJS and not about backend I’ve saved data in JSON and stored in a site called myjson.com which gives a unique URL for each JSON saved from which JSON data can be fetched.

I’ve used bootstrap for quickly styling the app. I wont be talking about styling in this tutorial. you can read more about bootstrap here

View live demo of app here – Movie DVD store using AngularJS

Lets start app development step by step :

1.Add AngularJS using script tag, create a module, use basic html and start angular using ng-app directive

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>

var myApp = angular.module('myApp',[]);

<html ng-app="myApp">

2.Add a controller with following dependencies $scope, $http, $location. $scope is used to store data, $http is used to make HTTP request to fetch json data, $location is used to change routes and URL.

myApp.controller('DataController', ['$scope', '$http', '$location', function($scope, $http, $location) { }]);

Add controller to body using ng-controller directive. We are using only one controller for whole app because this is a simple app and purely for learning purpose.

<body ng-controller="DataController">

3.Fetch movies data and set it to scope. $http service is used to fetch JSON data. JSON data is available at https://api.myjson.com/bins/4khft

This JSON is an array of objects and each object has movie name,image,buy price,rent price,storyline properties.

Ater getting JSON, set it to ‘$scope.movies’. http request may take a second or few seconds to load depending on the server speed and home page is shown blank till the request is complete as we are displaying movies list on homepage, so we should let the user know that data is being loaded using a loading image.

I added a loading image to main HTML file with ng-hide directive. ng-hide shows or hides an element based on the expression or variable in ng-hide. if variable is true then element is hidden, else element is unhidden. check code below :

<img ng-hide="loaded" src="http://imgh.us/ring.gif" />

$scope.loaded variable is added in DataController as $scope.loaded = false and set to true when data is loaded. so loading image is displayed until data is being loaded and hidden once data is loaded.

$scope.loaded = false; $http.get('https://api.myjson.com/bins/54jf7').success(function(data){ $scope.movies = data; $scope.loaded = true; });

4. configuring routes – we have the data, now lets configure routes and add templates with content for each route. This app need 4 routes, one for home with list of movies, one for confirm purchase, one for checkout and one for thankyou page.

myApp.config(['$routeProvider', '$locationProvider', function($routeProvider,$locationProvider){ $routeProvider .when('/home', { templateUrl: 'home.html' }) .when('/confirm', { templateUrl: 'confirm.html' }) .when('/checkout', { templateUrl: 'checkout.html' }) .when('/thankyou', { templateUrl: 'thankyou.html' }); $routeProvider.otherwise( { redirectTo: '/home' }); $locationProvider.html5Mode({ enabled: true, requireBase: false }); }]);

5. adding templates – This time we are using inline templates which means templates for each route are present in the same html file.

Inline templates are used by adding script tag with type=”text/ng-template” and id=”templatename.html”

<script type="text/ng-template" id="home.html"> <div ng-repeat="movie in movies" class="col-sm-12 col-lg-3 col-md-6"> <div class="thumbnail"> <img class="poster" ng-src="{{movie.image}}"> <div class="caption text-center"> <h4>{{movie.name}}</h4> <p><a ng-click="buy(movie)" class="btn btn-primary" role="button">Buy - {{movie.buy | currency:"$":0}}</a> <a ng-click="rent(movie)"class="btn btn-default" role="button">Rent - {{movie.rent | currency:"$":0}}</a></p> </div> </div> </div> </script>

The above code is template for /home route. ng-repeat directive is used to iterate through list of movies in $scope.movies and display movie name, image, buy button with buy price,rent button with rent price.

Currency filter is used on buy button text and rent button text to format with ‘$’ sign. ng-click directive is used on buttons to bind a click event which runs buy() function when button is clicked and also sends a specific movie object as parameter which will be used in the function. we have to define buy() and rent() functions in DataController

Adding functions : We need functions for buy button, rent button, checkout button in next page and pay button in the final page. These functions are used to set the movie which user wants to buy to ‘selectedMovie’ variable and change route to next page.

I’ve added a status variable which tracks whether user wants to buy or rent a movie and a shipping variable which has shipping cost. for simplicity we are using fixed shipping cost for all transactions.

$scope.buy = function(movie){ $scope.status = "buy" $scope.selectedMovie = movie; $location.path('/confirm'); }; $scope.rent = function(movie){ $scope.status = "rent" $scope.selectedMovie = movie; $location.path('/confirm'); }; $scope.checkout = function() { $location.path('/checkout'); } $scope.pay = function(){ $location.path('/thankyou') }; $scope.shipping = 2;

Adding confirm page template :

<script type="text/ng-template" id="confirm.html"> <ol class="breadcrumb"> <li><a href="home">Home</a></li> <li><a href="confirm">Buy {{selectedMovie.name}}</a></li> </ol> <h2>{{status === 'buy' ? 'Confirm DVD purchase':'Confirm rental purchase'}}</h2> <hr /> <div class="row"> <div class="col-lg-3"><img ng-src="{{selectedMovie.image}}"> <h4>{{selectedMovie.name}}</h4> </div> <div class="col-lg-6"> <h4 class="storyline">Storyline</h4> <p>{{selectedMovie.storyline}}</div> <div class="col-lg-3"> <div class="row"> <div class="col-lg-6">Price :</div> <div class="col-lg-6"><span class="pull-right">{{status==='buy'?selectedMovie.buy:selectedMovie.rent}}</span></div> </div> <div class="row"> <div class="col-lg-6">shipping :</div> <div class="col-lg-6"><span class="pull-right">{{shipping | currency}}</span></div> </div> <hr /> <div class="row"> <div class="col-lg-6">Total :</div> <div class="col-lg-6"><span class="pull-right">{{status==='buy'?selectedMovie.buy + shipping :selectedMovie.rent + shipping | currency}}</span></div> </div> <hr /> <div class="row"> <div class="col-lg-12"><button class="btn btn-primary pull-right" ng-click="checkout()">checkout</button></div> </div> </div> </div> </script>

Things to note in the above template:

1.we have set selectedMovie variable when user clicks buy or rent, that variable is used now for displaying selected movie name and storyline in lines 4 and 13.

2.we have set status variable to buy or rent when user clicks buy or rent, In line 6 Confirm DVD purchase is displayed when status is buy and Confirm rental purchase is displayed when status is rent, same with the price in line 18.

3.In line 27, total cost is displayed by adding buy price or rent price with shipping cost and dispalyed. checkout() function is binded to checkout button which takes user to checkout page.

Adding checkout template :

<script type="text/ng-template" id="checkout.html"> <ol class="breadcrumb"> <li><a href="home">Home</a></li> <li><a href="confirm">Buy {{selectedMovie.name}}</a></li> <li><a href="checkout">checkout</a></li> </ol> <div class="row"> <div class="col-md-4"></div> <div class="col-md-4"> <form> <div class='form-row'> <div class='col-xs-12 form-group required'> <label class='control-label'>Name on Card</label> <input class='form-control' size='4' type='text' value="John doe"> </div> </div> <div class='form-row'> <div class='col-xs-12 form-group card required'> <label class='control-label'>Card Number</label> <input autocomplete='off' class='form-control' size='20' type='text' value="4234 5678 9423 8765"> </div> </div> <div class='form-row'> <div class='col-xs-4 form-group cvc required'> <label class='control-label'>CVC</label> <input autocomplete='off' class='form-control card-cvc' placeholder='ex. 311' value='311' size='4' type='text'> </div> <div class='col-xs-4 form-group expiration required'> <label class='control-label'>Expiration</label> <input class='form-control card-expiry-month' placeholder='MM' size='2' type='text' value='08'> </div> <div class='col-xs-4 form-group expiration required'> <label class='control-label'> </label> <input class='form-control card-expiry-year' placeholder='YYYY' size='4' type='text' value='2036'> </div> </div> <div class='form-row'> <div class='col-md-12'> <div class='form-control total btn btn-info'> Total: <span class='amount'>{{status ==='buy'?selectedMovie.buy + shipping : selectedMovie.rent + shipping | currency}}</span> </div> </div> </div> <div class='form-row'> <div class='col-md-12 form-group'> <button class='form-control btn btn-primary submit-button' ng-click="pay()">Pay »</button> </div> </div> </form> </div> <div class="col-md-4"></div> </div> </script>

Add checkout template and thankyou template :

checkout template has just a form where user can enter credit card details and a pay button which would navigate to next page which shows thank you for purchasing along with movie name. movie name is again displayed using selectedMovie.name

Have a look at complete source code here : Movie DVD store source code

See the Pen Movie dvd store using AngularJS – Tutorial by Ranjith (@Ranjithkumar10) on CodePen.0

This app is purely for learning angualrJS and doesn’t include any backend and payment integration. With this we have completed developing a simple store app using angularJS.



Wrapping up

This was a long tutorial and we’ve come to an end. There is a lot more that can be done with AngularJS. I tried to explain commonly used concepts and directives of angularJS so that beginners can have a quick start. You can always refer AngularJS official documentation to explore more concepts – AngularJS docs

If you have any questions or feedback, comment below.

