Featured Post

tutorials-1449906716439

AngularJS is an open source web application framework. It was originally developed in 2009 by Misko Hevery and Adam Abrons. It is now maintained by Google. Its latest version is 1.4.3.

Definition of AngularJS as put by its official documentation is as follows ?

AngularJS is a powerful JavaScript based development framework to create RICH Internet Application(RIA).

AngularJS provides developers options to write client side application (using JavaScript) in a clean MVC(Model View Controller) way.

Application written in AngularJS is cross-browser compliant. AngularJS automatically handles JavaScript code suitable for each browser.

AngularJS is open source, completely free, and used by thousands of developers around the world. It is licensed under the Apache License version 2.0.

Overall, AngularJS is a framework to build large scale and high performance web application while keeping them as easy-to-maintain.

Following are most important core features of AngularJS ?

Data-binding ? It is the automatic synchronization of data between model and view components.

Scope ? These are objects that refer to the model. They act as a glue between controller and view.

Controller ? These are JavaScript functions that are bound to a particular scope.

Services ? AngularJS come with several built-in services for example $http to make a XMLHttpRequests. These are singleton objects which are instantiated only once in app.

Filters ? These select a subset of items from an array and returns a new array.

Directives ? Directives are markers on DOM elements (such as elements, attributes, css, and more). These can be used to create custom HTML tags that serve as new, custom widgets. AngularJS has built-in directives (ngBind, ngModel...)

Templates ? These are the rendered view with information from the controller and model. These can be a single file (like index.html) or multiple views in one page using "partials".

Routing ? It is concept of switching views.

Model View Whatever ? MVC is a design pattern for dividing an application into different parts (called Model, View and Controller), each with distinct responsibilities. AngularJS does not implement MVC in the traditional sense, but rather something closer to MVVM (Model-View-ViewModel). The Angular JS team refers it humorously as Model View Whatever.

Deep Linking ? Deep linking allows you to encode the state of application in the URL so that it can be bookmarked. The application can then be restored from the URL to the same state.

Dependency Injection ? AngularJS has a built-in dependency injection subsystem that helps the developer by making the application easier to develop, understand, and test.

Following diagram depicts some important parts of AngularJS which we will discuss in detail in the subsequent chapters.

AngularJS provides capability to create Single Page Application in a very clean and maintainable way.

AngularJS provides data binding capability to HTML thus giving user a rich and responsive experience

AngularJS code is unit testable.

AngularJS uses dependency injection and make use of separation of concerns.

AngularJS provides reusable components.

With AngularJS, developer write less code and get more functionality.

In AngularJS, views are pure html pages, and controllers written in JavaScript do the business processing.

On top of everything, AngularJS applications can run on all major browsers and smart phones including Android and iOS based phones/tablets.

Though AngularJS comes with lots of plus points but same time we should consider the following points ?

Not Secure ? Being JavaScript only framework, application written in AngularJS are not safe. Server side authentication and authorization is must to keep an application secure.

Not degradable ? If your application user disables JavaScript then user will just see the basic page and nothing more.

The AngularJS framework can be divided into following three major parts ?

ng-app ? This directive defines and links an AngularJS application to HTML.

ng-model ? This directive binds the values of AngularJS application data to HTML input controls.

ng-bind ? This directive binds the AngularJS Application data to HTML tags.

You really do not need to set up your own environment to start learning AngularJS. Reason is very simple, we already have set up AngularJS environment online, so that you can execute all the available examples online at the same time when you are doing your theory work. This gives you confidence in what you are reading and to check the result with different options. Feel free to modify any example and execute it online.

Try the following example using Try it option available at the top right corner of the below sample code box ?

For most of the examples given in this tutorial, you will find Try it option, so just make use of it and enjoy your learning.

In this chapter we will discuss about how to set up AngularJS library to be used in web application development. We will also briefly study the directory structure and its contents.

When you open the link https://angularjs.org/, you will see there are two options to download AngularJS library ?

View on GitHub ? Click on this button to go to GitHub and get all of the latest scripts.

Download ? Or click on this button, a screen as below would be seen ?

This screen gives various options of using Angular JS as follows ?

Downloading and hosting files locally

There are two different options legacy and latest. The names itself are self descriptive. legacy has version less than 1.2.x and latest has 1.4.x version.

We can also go with the minified, uncompressed or zipped version.

CDN access ? You also have access to a CDN. The CDN will give you access around the world to regional data centers that in this case, Google host. This means using CDN moves the responsibility of hosting files from your own servers to a series of external ones. This also offers an advantage that if the visitor to your webpage has already downloaded a copy of AngularJS from the same CDN, it won't have to be re-downloaded.

Now let us write a simple example using AngularJS library. Let us create an HTML file myfirstexample.html as below ?

Following sections describe the above code in detail ?

We have included the AngularJS JavaScript file in the HTML page so we can use AngularJS ?

Check the latest version of AngularJS on their official website.

Next we tell what part of the HTML contains the AngularJS app. This done by adding the ng-app attribute to the root HTML element of the AngularJS app. You can either add it to html element or body element as shown below ?

The view is this part ?

ng-controller tells AngularJS what controller to use with this view. helloTo.title tells AngularJS to write the "model" value named helloTo.title to the HTML at this location.

The controller part is ?

This code registers a controller function named HelloController in the angular module named myapp. We will study more about modules and controllers in their respective chapters. The controller function is registered in angular via the angular.module(...).controller(...) function call.

The $scope parameter passed to the controller function is the model. The controller function adds a helloTo JavaScript object, and in that object it adds a title field.

Save the above code as myfirstexample.html and open it in any browser. You will see an output as below ?

When the page is loaded in the browser, following things happen ?

HTML document is loaded into the browser, and evaluated by the browser. AngularJS JavaScript file is loaded, the angular global object is created. Next, JavaScript which registers controller functions is executed.

Next AngularJS scans through the HTML to look for AngularJS apps and views. Once view is located, it connects that view to the corresponding controller function.

Next, AngularJS executes the controller functions. It then renders the views with data from the model populated by the controller. The page is now ready.

Model View Controller or MVC as it is popularly called, is a software design pattern for developing web applications. A Model View Controller pattern is made up of the following three parts ?

Model ? It is the lowest level of the pattern responsible for maintaining data.

View ? It is responsible for displaying all or a portion of the data to the user.

Controller ? It is a software Code that controls the interactions between the Model and View.

MVC is popular because it isolates the application logic from the user interface layer and supports separation of concerns. The controller receives all requests for the application and then works with the model to prepare any data needed by the view. The view then uses the data prepared by the controller to generate a final presentable response. The MVC abstraction can be graphically represented as follows.

The model is responsible for managing application data. It responds to the request from view and to the instructions from controller to update itself.

A presentation of data in a particular format, triggered by the controller's decision to present the data. They are script-based template systems such as JSP, ASP, PHP and very easy to integrate with AJAX technology.

The controller responds to user input and performs interactions on the data model objects. The controller receives input, validates it, and then performs business operations that modify the state of the data model.

AngularJS is a MVC based framework. In the coming chapters, we will see how AngularJS uses MVC methodology.

Before we start with creating actual HelloWorld application using AngularJS, let us see what are the actual parts of a AngularJS application. An AngularJS application consists of following three important parts ?

ng-app ? This directive defines and links an AngularJS application to HTML.

ng-model ? This directive binds the values of AngularJS application data to HTML input controls.

ng-bind ? This directive binds the AngularJS Application data to HTML tags.

Being a pure JavaScript framework, It can be added using <Script> tag.

Use above mentioned three steps in an HTML page.

testAngularJS.htm

Open textAngularJS.htm in a web browser. Enter your name and see the result.

ng-app directive indicates the start of AngularJS application.

ng-model directive then creates a model variable named "name" which can be used with the html page and within the div having ng-app directive.

ng-bind then uses the name model to be displayed in the html span tag whenever user input something in the text box.

Closing</div> tag indicates the end of AngularJS application.

AngularJS directives are used to extend HTML. These are special attributes starting with ng- prefix. We're going to discuss following directives ?

ng-app ? This directive starts an AngularJS Application.

ng-init ? This directive initializes application data.

ng-model ? This directive defines the model that is variable to be used in AngularJS.

ng-repeat ? This directive repeats html elements for each item in a collection.

ng-app directive starts an AngularJS Application. It defines the root element. It automatically initializes or bootstraps the application when web page containing AngularJS Application is loaded. It is also used to load various AngularJS modules in AngularJS Application. In following example, we've defined a default AngularJS application using ng-app attribute of a div element.

ng-init directive initializes an AngularJS Application data. It is used to put values to the variables to be used in the application. In following example, we'll initialize an array of countries. We're using JSON syntax to define array of countries.

ng-model directive defines the model/variable to be used in AngularJS Application. In following example, we've defined a model named "name".

ng-repeat directive repeats html elements for each item in a collection. In following example, we've iterated over array of countries.

Following example will showcase all the above mentioned directives.

testAngularJS.htm

Open textAngularJS.htm in a web browser. Enter your name and see the result.

Expressions are used to bind application data to html. Expressions are written inside double braces like {{ expression}}. Expressions behaves in same way as ng-bind directives. AngularJS application expressions are pure javascript expressions and outputs the data where they are used.

Following example will showcase all the above mentioned expressions.

testAngularJS.htm

Open textAngularJS.htm in a web browser. See the result.

AngularJS application mainly relies on controllers to control the flow of data in the application. A controller is defined using ng-controller directive. A controller is a JavaScript object containing attributes/properties and functions. Each controller accepts $scope as a parameter which refers to the application/module that controller is to control.

Here we've declared a controller studentController using ng-controller directive. As a next step we'll define the studentController as follows ?

studentController defined as a JavaScript object with $scope as argument.

$scope refers to application which is to use the studentController object.

$scope.student is property of studentController object.

firstName and lastName are two properties of $scope.student object. We've passed the default values to them.

fullName is the function of $scope.student object whose task is to return the combined name.

In fullName function we're getting the student object and then return the combined name.

As a note, we can also defined the controller object in separate JS file and refer that file in the html page.

Now we can use studentController's student property using ng-model or using expressions as follows.

We've bounded student.firstName and student.lastname to two input boxes.

We've bounded student.fullName() to HTML.

Now whenever you type anything in first name and last name input boxes, you can see the full name getting updated automatically.

Following example will showcase use of controller.

testAngularJS.htm

Open textAngularJS.htm in a web browser. See the result.

Filters are used to change modify the data and can be clubbed in expression or directives using pipe character. Following is the list of commonly used filters.

Add uppercase filter to an expression using pipe character. Here we've added uppercase filter to print student name in all capital letters.

Add lowercase filter to an expression using pipe character. Here we've added lowercase filter to print student name in all lowercase letters.

Add currency filter to an expression returning number using pipe character. Here we've added currency filter to print fees using currency format.

To display only required subjects, we've used subjectName as filter.

To order subjects by marks, we've used orderBy marks.

Following example will showcase all the above mentioned filters.

testAngularJS.htm

Open textAngularJS.htm in a web browser. See the result.

Table data is normally repeatable by nature. ng-repeat directive can be used to draw table easily. Following example states the use of ng-repeat directive to draw a table.

Table can be styled using CSS Styling.

Following example will showcase all the above mentioned directive.

testAngularJS.htm

Open textAngularJS.htm in a web browser. See the result.

Following directives can be used to bind application data to attributes of HTML DOM Elements.

Add ng-disabled attribute to a HTML button and pass it a model. Bind the model to an checkbox and see the variation.

Add ng-show attribute to a HTML button and pass it a model. Bind the model to an checkbox and see the variation.

Add ng-hide attribute to a HTML button and pass it a model. Bind the model to an checkbox and see the variation.

Add ng-click attribute to a HTML button and update a model. Bind the model to html and see the variation.

Following example will showcase all the above mentioned directives.

testAngularJS.htm

Open textAngularJS.htm in a web browser. See the result.

AngularJS supports modular approach. Modules are used to separate logics say services, controllers, application etc. and keep the code clean. We define modules in separate js files and name them as per the module.js file. In this example we're going to create two modules.

Application Module ? used to initialize an application with controller(s).

Controller Module ? used to define the controller.

mainApp.js

Here we've declared an application mainApp module using angular.module function. We've passed an empty array to it. This array generally contains dependent modules.

studentController.js

Here we've declared a controller studentController module using mainApp.controller function.

Here we've used application module using ng-app directive and controller using ng-controller directive. We've imported mainApp.js and studentController.js in the main html page.

Following example will showcase all the above mentioned modules.

testAngularJS.htm

mainApp.js

studentController.js

Open textAngularJS.htm in a web browser. See the result.

AngularJS enriches form filling and validation. We can use ng-click to handle AngularJS click on button and use $dirty and $invalid flags to do the validations in seemless way. Use novalidate with a form declaration to disable any browser specific validation. Forms controls makes heavy use of Angular events. Let's have a quick look on events first.

AngularJS provides multiple events which can be associated with the HTML controls. For example ng-click is normally associated with button. Following are supported events in Angular JS.

Reset data of a form using on-click directive of a button.

Following can be used to track error.

$dirty ? states that value has been changed.

$invalid ? states that value entered is invalid.

$error ? states the exact error.

Following example will showcase all the above mentioned directives.

testAngularJS.htm

Open textAngularJS.htm in a web browser. See the result.

HTML does not support embedding html pages within html page. To achieve this functionality following ways are used ?

Using Ajax ? Make a server call to get the corresponding html page and set it in innerHTML of html control.

Using Server Side Includes ? JSP, PHP and other web side server technologies can include html pages within a dynamic page.

Using AngularJS, we can embedded HTML pages within a HTML page using ng-include directive.

tryAngularJS.htm

main.htm

subjects.htm

To run this example, you need to deploy textAngularJS.htm, main.htm and subjects.htm to a webserver. Open textAngularJS.htm using url of your server in a web browser. See the result.

AngularJS provides $http control which works as a service to read data from the server. The server makes a database call to get the desired records. AngularJS needs data in JSON format. Once the data is ready, $http can be used to get the data from server in the following manner ?

Here, the file data.txt contains student records. $http service makes an ajax call and sets response to its property students. students model can be used to draw tables in HTML.

To execute this example, you need to deploy testAngularJS.htm and data.txt file to a web server. Open the file testAngularJS.htm using the URL of your server in a web browser and see the result.

AngularJS supports Single Page Application via multiple views on a single page. To do this AngularJS has provided ng-view and ng-template directives and $routeProvider services.

ng-view tag simply creates a place holder where a corresponding view (html or ng-template view) can be placed based on the configuration.

Define a div with ng-view within the main module.

ng-template directive is used to create an html view using script tag. It contains "id" attribute which is used by $routeProvider to map a view with a controller.

Define a script block with type as ng-template within the main module.

$routeProvider is the key service which set the configuration of urls, map them with the corresponding html page or ng-template, and attach a controller with the same.

Define a script block with type as ng-template within the main module.

Define a script block with main module and set the routing configuration.

Following are the important points to be considered in above example.

$routeProvider is defined as a function under config of mainApp module using key as '$routeProvider'.

$routeProvider.when defines a url "/addStudent" which then is mapped to "addStudent.htm". addStudent.htm should be present in the same path as main html page.If htm page is not defined then ng-template to be used with id="addStudent.htm". We've used ng-template.

"otherwise" is used to set the default view.

"controller" is used to set the corresponding controller for the view.

Following example will showcase all the above mentioned directives.

testAngularJS.htm

Open textAngularJS.htm in a web browser. See the result.

Scope is a special javascript object which plays the role of joining controller with the views. Scope contains the model data. In controllers, model data is accessed via $scope object.

Following are the important points to be considered in above example.

$scope is passed as first argument to controller during its constructor definition.

$scope.message and $scope.type are the models which are to be used in the HTML page.

We've set values to models which will be reflected in the application module whose controller is shapeController.

We can define functions as well in $scope.

Scope are controllers specific. If we defines nested controllers then child controller will inherit the scope of its parent controller.

Following are the important points to be considered in above example.

We've set values to models in shapeController.

We've overridden message in child controller circleController. When "message" is used within module of controller circleController, the overridden message will be used.

Following example will showcase all the above mentioned directives.

testAngularJS.htm

Open textAngularJS.htm in a web browser. See the result.

AngularJS supports the concepts of "Separation of Concerns" using services architecture. Services are javascript functions and are responsible to do a specific tasks only. This makes them an individual entity which is maintainable and testable. Controllers, filters can call them as on requirement basis. Services are normally injected using dependency injection mechanism of AngularJS.

AngularJS provides many inbuilt services for example, $http, $route, $window, $location etc. Each service is responsible for a specific task for example, $http is used to make ajax call to get the server data. $route is used to define the routing information and so on. Inbuilt services are always prefixed with $ symbol.

There are two ways to create a service.

Using factory method, we first define a factory and then assign method to it.

Using service method, we define a service and then assign method to it. We've also injected an already available service to it.

Following example will showcase all the above mentioned directives.

testAngularJS.htm

Open textAngularJS.htm in a web browser. See the result.

Dependency Injection is a software design pattern in which components are given their dependencies instead of hard coding them within the component. This relieves a component from locating the dependency and makes dependencies configurable. This helps in making components reusable, maintainable and testable.

AngularJS provides a supreme Dependency Injection mechanism. It provides following core components which can be injected into each other as dependencies.

value is simple javascript object and it is used to pass values to controller during config phase.

factory is a function which is used to return value. It creates value on demand whenever a service or controller requires. It normally uses a factory function to calculate and return the value.

service is a singleton javascript object containing a set of functions to perform certain tasks. Services are defined using service() functions and then injected into controllers.

provider is used by AngularJS internally to create services, factory etc. during config phase(phase during which AngularJS bootstraps itself). Below mention script can be used to create MathService that we've created earlier. Provider is a special factory method with a method get() which is used to return the value/service/factory.

constants are used to pass values at config phase considering the fact that value can not be used to be passed during config phase.

Following example will showcase all the above mentioned directives.

testAngularJS.htm

Open textAngularJS.htm in a web browser. See the result.

Custom directives are used in AngularJS to extend the functionality of HTML. Custom directives are defined using "directive" function. A custom directive simply replaces the element for which it is activated. AngularJS application during bootstrap finds the matching elements and do one time activity using its compile() method of the custom directive then process the element using link() method of the custom directive based on the scope of the directive. AngularJS provides support to create custom directives for following type of elements.

Element directives ? Directive activates when a matching element is encountered.

Attribute ? Directive activates when a matching attribute is encountered.

CSS ? Directive activates when a matching css style is encountered.

Comment ? Directive activates when a matching comment is encountered.

Define custom html tags.

Define custom directive to handle above custom html tags.

Define controller to update the scope for directive. Here we are using name attribute's value as scope's child.

Open textAngularJS.htm in a web browser. See the result.

AngularJS supports inbuilt internationalization for three types of filters currency, date and numbers. We only need to incorporate corresponding js according to locale of the country. By default it handles the locale of the browser. For example, to use Danish locale, use following script.

testAngularJS.htm

Open textAngularJS.htm in a web browser. See the result.

testAngularJS.htm

Open textAngularJS.htm in a web browser. See the result.

� Copyright 2015. All Rights Reserved.

Comments

Popular posts from this blog

[Inside AdSense] Understanding your eCPM (effective cost per thousand impress...