0% found this document useful (0 votes)
96 views

Introduction To AngularJS

AngularJS is a JavaScript framework that allows developers to create single-page applications. It uses Model-View-Whatever architecture, where the exact pattern is not important. AngularJS simplifies development through two-way data binding between models and views. Controllers are JavaScript functions that are used to add logic to views. Scopes link controllers and views by holding the model data that is passed to views using two-way data binding.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views

Introduction To AngularJS

AngularJS is a JavaScript framework that allows developers to create single-page applications. It uses Model-View-Whatever architecture, where the exact pattern is not important. AngularJS simplifies development through two-way data binding between models and views. Controllers are JavaScript functions that are used to add logic to views. Scopes link controllers and views by holding the model data that is passed to views using two-way data binding.
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 17

Introduction to AngularJS

AngularJS as it says is a Superheroic JavaScript MVW framework. It assists with


running single-page applications. Its goal is to augment browser-based
applications with modelviewcontroller (MVC) capability, in an effort to make
both development and testing easier.
AngularJS takes declarative programming to whole new level. It adapts and
extends traditional HTML to better serve dynamic content through two-way databinding that allows for the automatic synchronization of models and views.

MVW Model View Whatever


There are many software architecture pattern which separates the representation
of information from the users interaction with it. The central ideas behind these
patterns are code reusability and separation of concerns. The most famous
pattern that is used widely today is MVC or Model-View-Controller. Similar to
MVC, there is another pattern called MVP or Model-View-Presenter. The MVP is
based on MVC and the presenter assumes the functionality of the middle-man
(played by the controller in MVC). In MVP, all presentation logic is pushed to the
presenter. Eventually, the model becomes strictly a domain model. And then
there are other patterns such as MVVM or Model-View-View-Model.
Angular doesnt care actually what software architecture pattern you want to use
in your app. And thus the pattern MVW or Model-View-Whatever. A basic concept
of MVW is that all definitions are associated with a named Module. Modules can
then be aggregated to form complete web applications. Modules can depend on
one another, so that including a single Module in your WebApplication may bring
along additional functionality on which that Module depends. Angular JS provides
you with rich set of APIs to define these modules and linked them together with
dependency injection. We will see this in great detail in next few articles.
Hello World, AngularJS
Before we get into any theory, let us get our hands dirty with some actual Angular
code. That way would learn a great deal of whats happening.
In order to write a hello world application in Angular, all we have to do is it include
Angular JS JavaScript in our HTML document.

Example 0:

<!DOCTYPE html>
<html ng-app>
<head>
<title>Angular JS First Example</title>
<script type="text/javascript"
src="angular.min.js"></script>
</head>
<body>
Write some text in textbox:
<input type="text" ng-model="sometext" />
<h1>Hello {{ sometext }}</h1>
</body>
</html>

Output:

ng-app
First thing that we notice is an attribute ng-app within <html> tag. This attribute
tells the Angular to be active in this portion of the page. So in our case entire
document. If you want to enable Angular only at specific location in your
webpage then you can define ng-app attribute to any DIV or other tag.
In case you are building app that also works with IE7, add id=ngapp. For
example:
<html ng-app id="ng-app">

If you choose to use the old style directive syntax ng: then include xmlnamespace in html to make IE happy.
<html xmlns:ng="http://angularjs.org">

ng-model and Two way data binding


We define attribute ng-model in textbox as ng-model=sometext. ng-model binds
the state of textbox with model value. In our case we define a model sometext.
This model value is bound with the value of textbox using ng-model attribute.
Thus when the textbox value changes, Angular automatically changes the model
sometext with this value. This is called Two way data binding. Similarly, if we
change the model value than Angular will change the value of textbox. Two way
data binding is the core of Angulars magical spell. It just works. Youll get to
know about it more once we start adding complexity in our application.
AngularJS two-way data binding is its most notable feature and reduces the
amount of code written by relieving the server backend from templating
responsibilities.
{{ sometext }}
Note how we wrap our model value in double curly braces. This tell Angular to
bind the value of model sometext in place of {{ sometext }}.
Thus any change in sometext model value changes the text inside <h1> tag.

ng-show / ng-hide
Now lets further modify our demo and add one more Angular attribute ng-show.
In below code, we added attribute ng-show=sometext to <h1> tag.
If you want to change and play around with code use this JSFiddle:
http://jsfiddle.net/viralpatel/ppgsS/
In this demo, the text Hello does not appear unless we type anything in textbox.
We added just one small attribute to <H1> tag and see how the functionality
changed!.
ng-show attribute conditionally show an element, depending on the value of a
boolean expression. Similar to ng-show you can also use ng-hide, which exactly
does opposite of ng-show.
Note that until now we have not written any JavaScript code at all. Still our
application became so dynamic.

AngularJS Filters
AngularJS provides powerful mechanism to modify the data on the go using
Filters. Filters typically transform the data to a new data type, formatting the data
in the process. The general syntax for using filter is:
{{ expression | filter }}
You can use more than filter on an expression by chaining them like:
{{ expression | filter1 | filter2 }}
AngularJS by default provide few filters that we can use in our app. It is also
possible to define your own custom filters. For now we will just check filters that
Angular provide with framework.
Filter uppercase and lowercase
As its name suggest, this filter convert the expression into uppercase letters. Lets
check a quick demo. Lets modify few lines from our above example and use
uppercase filter.

Example :
<!DOCTYPE html>
<html ng-app>
<head>
<title>Mmcc Computer Centre AngularJS</title>
<script type="text/javascript"
src="angular.min.js"></script>
</head>
<body>
Write some text in textbox:
<input type="text" ng-model="sometext" />
<h1>Hello {{ sometext }}</h1>
<h4>Uppercase: {{ sometext | uppercase }}</h4>
<h4>Lowercase: {{ sometext | lowercase }}</h4>
</body>
</html>

Output:

Notice when you type in the textbox, the value is converted to upper and lower
case depending on the filter we used.
Similarly, Angular provides some more filters like:
date
Usage:
{{ date_expression | date[:format] }}
Formats date to a string based on the requested format. Read Angular
documentation to know more about format.
number
Usage:
{{ number_expression | number[:fractionSize] }}
Formats a number as text. If the input is not a number an empty string is
returned.
There are more filters like json, limitTo, filter, orderBy. We will go through them in
next few articles as and when we use them.

AngularJS Controller
Controllers are nothing but plain JavaScript functions which are bound to a
particular scope. Dont worry if this sounds gibberish. Shortly this all will make
sense once we create a small Hello World using controller. Controllers are used
to add logic to your view. Views are HTML pages. These pages simply shows the
data that we bind to them using two-way data binding in Angular (Note: Two-way
data binding is explained in previous tutorial). Basically it is Controllers
responsibility to glue the Model (data) with the View.

1. What are Scopes?


Before we get into Controllers let us understand Scopes. Scope is nothing but an
object that Glues the View with Controller. They hold the Model data that we
need to pass to view. Scope uses Angulars two-way data binding to bind model
data to view.
Imaging $scope as an object that links Controller to the View. It is controllers
responsibility to initialize the data that the view needs to display. This is done by
making changes to $scope.

Example:
<!DOCTYPE html>
<html ng-app>
<head>
<title>MMCC AngularJS </title>
<script type="text/javascript"
src="angular.min.js"></script>
</head>
<body>
<div ng-controller="ContactController">
Email:<input type="text" ng-model="newcontact"/>
<button ng-click="add()">Add</button>
<h2>Contacts</h2>
<ul>
<li ng-repeat="contact in contacts"> {{ contact }} </li>
</ul>
</div>
<script type="text/javascript">
function ContactController($scope) {
$scope.contacts = ["[email protected]", "[email protected]"];
$scope.add = function() {

$scope.contacts.push($scope.newcontact);
$scope.newcontact = "";
}
}
</script>
</body>
</html>

Output:

1.2. ng-controller
This attribute defines a Controller to be bound with the view. In this case we
defined a controller called ContactController in DIV using ng-controller attribute.
Thus whatever we put inside that DIV, the ContactController will have its
influence on it.
ContactController is nothing but a plain vanilla JavaScript function. In the demo
we defined it as function. Also see the definition of ContactController function.
There is an object $scope which we pass as an argument. This object is used to
bind the controller with view. When AngularJS initialize this controller, it
automatically creates and injects the $scope object to this function using
dependency injection (More on dependency injection in coming tutorials). For
now just note that the $scope object is created by Angular and injected in this
controller function.
1.3. ng-repeat
Notice how we displayed a list of contacts using an attribute ng-repeat.
<li ng-repeat="contact in contacts">{{ contact }}</li>

ngRepeat is one of the most used AngularJS attribute. It iterate through an array
and bind the view with each element. So in our example it creates <li> tag for
each item within contacts array. ngRepeat takes expression as argument. In our
case contact in contacts where contact is user defined variable and contacts is
an array within $scope.
In our final demo in this tutorial, we will use ng-repeat to iterate through an array
of objects and paint each property in a table.
2. Initial state of a scope object
Typically, when you create an application you need to set up an initial state for an
Angular scope. In our case we need initial state to be list of contacts.
On $scope object, we defined an array called contacts:
$scope.contacts = ["[email protected]", "[email protected]"]
When Angular initilize this function (ContactController), it automatically creates
this array and binds it in $scope object. Then in our view we display the array
using ng-repeat attribute.
Thus, $scope provides us with a way to pass/retrieve objects from Controller to
View and vice-versa.
2.1. ng-click
It is also possible to define functions on $scope and use the same in View. In our
demo, we created a function add() on $scope and use it on Add button click:
$scope.add = function() {
...
}
The function add() is bound to Add button using an attribute ng-click. ng-click
binds the click event on the button or link or any clickable element with the
function that is defined within $scope. So in this case, whenever Add button is
clicked, the add() method on $scope will be called.
In add() method we add (or push) a string in contacts array. This is the string that
user types in textbox. Note that we bind textbox using ng-model attribute.
<input type="text" ng-model="contact" ...
This textboxs value we got in $scope.contact as we bind it using ng-model
attribute.

How to define a Controller


So we got some basic idea of what Controllers are. Just plain JavaScript
functions that we add in an Angular application to add some business logic and
bind the view with model.
In the above demo, we defined controller as JavaScript function. While this is the
easiest way to define them, but is certainly not advisable one. If your application
grows, soon youll have bunch of controllers lying here and there in code
polluting the JavaScript namespace.
So instead of defining controller as:
function ContactController($scope) {
//...
}
We should define Controller within Modules.

AngularJS Modules
So what-the-heck are modules? Well, modules are the logical entities that you
divide you app in. So your app can contain several modules (like Transaction,
Report, etc.). Each module represent a logical entity within the app.

Furthermore, each modules have several Controllers. As referred in above


diagram, a module can contain one or more controllers and views. We havent

touch based on Views. We will see how each module can be linked with view
using Routing in AngularJS in our next tutorial. For now just assume that each
controller has one or more views linked to it.
So in this case, we can add one or more controllers to a module. Let us check
the syntax to create a module and add controller to it:
var myApp = angular.module('myApp',[]);
myApp.controller('ContactController', ['$scope', function($scope) {
$scope.contacts = ["[email protected]", "[email protected]"];
$scope.add = function() {
$scope.contacts.push($scope.contact);
$scope.contact = "";
}
}]);
In above example we created a module called myApp using angular.module()
method. Then we added a controller ContactController to this module. This is just
an alternate way of defining a controller but recommended one.
Notice how controller is declared using myApp.controller() method. We passed
an array to this method. First argument of array is string $scope and next is the
function itself that represent ContactController. We explicitly told Angular that we
have one argument (dependency) to our ContactController which is $scope. This
is useful when you Minify or obfuscate JavaScript for production release. In that
case the argument $scope might be renamed to $s, but because we defined
string $scope as first argument, Angular is aware that first dependency to this
controller is $scope object.

Nested Controllers
We can declare the scope of controller in our HTML page using ng-controller
attribute. For example:
<div ng-controller="CarController">
...
</div>
We can declare number of controllers and nest them within each other. For
example:

Example:
<!DOCTYPE html>
<html ng-app>
<head>
<title>MMCC AngularJS </title>
<script type="text/javascript"
src="angular.min.js"></script>
</head>
<body>
<div ng-controller="CarController">
My name is {{ name }} and I am a {{ type }}
<div ng-controller="BMWController">
My name is {{ name }} and I am a {{ type }}
<div ng-controller="BMWMotorcycleController">
My name is {{ name }} and I am a {{ type }}
</div>
</div>
</div>
<script>
function CarController($scope) {
$scope.name = 'Car';
$scope.type = 'Car';
}
function BMWController($scope) {
$scope.name = 'BMW';
}
function BMWMotorcycleController($scope) {
$scope.name = 'BMWMotorade';
$scope.type = 'Motorcycle';
}
</script></body>
</html>

Output:

In above demo, notice how each nested Controllers scope override the scope of
parents controller. First we defined a controller CarController which defines two
variables name and type within scope. Next BMWController is nested within
CarController using ng-controller attribute. BMWController overrides name
attribute and change it to BMW. It does not change type attribute so type attribute
is still Car.
BMWMotorcycleController is the inner-most controller defined within controllers
hierarchy. It overrides both name and type attribute of scope.
This way you can nest one controller within another and take advantage of
parent controllers attributes whenever needed.

Inheritance in Controllers
In order to take advantage of inheritance of scope in Nested controllers, one has
to define Controllers one into another using ng-controller attribute. Sometimes
you dont want to define controllers like this but still want to use power of
inheritance within controllers. May be you want to put common logic into
BaseController and use it in all the child controllers.
In order to achieve this, we must use $injector object that AngularJS provides.

Example:
<!DOCTYPE html>
<html ng-app>
<head>
<title>MMCC AngularJS </title>
<script type="text/javascript"
src="angular.min.js"></script>
</head>
<body>
<div ng-controller="CarController">
My name is {{ name }} and I am a {{ type }}
<div ng-controller="BMWController">
My name is {{ name }} and I am a {{ type }}
<button ng-click="clickme()">Click Me</button>
</div>
<script>
function CarController($scope) {
$scope.name = 'Car';
$scope.type = 'Car';
$scope.clickme = function() {
alert('This is parent controller "CarController" calling');
}
}
function BMWController($scope, $injector) {
$injector.invoke(CarController, this, {$scope: $scope});
$scope.name = 'BMW';
}
</script>
</body>
</html>

Output:

We define two controllers, CarController and BMWController. CarController


defines two attributes name and type on $scope and also defines one method
clickme().
BMWController just override name attribute. Notice that it does not have name
and clickme defined within its body. These attributes are defined by parent
controller in this case CarController. Within BMWController, we initialize
CarController and bind it into current scope using $injector.invoke() method.
Once this is done, notice how in HTML page the BMWController points to its
parents attributes.

End to end application using AngularJS Controller


Let us apply the knowledge that we acquired so far and create a
ContactManager application. Following are some basic requirements of this
application:

User can add new contact (name, email address and phone number)
List of contacts should be shown
User can delete any contact from contact list
User can edit any contact from contact list

Following is the HTML code which defines a FORM to save new contact and edit
contact. And also it defines a table where contacts can be viewed.

Example:
<!DOCTYPE html>
<html ng-app>
<head>
<title>MMCC AngularJS </title>
<script type="text/javascript"
src="angular.min.js"></script>
</head>
<body>
<div ng-controller="ContactController">
<form>
<label>Name</label>
<input type="text" name="name" ng-model="newcontact.name"/>
<label>Email</label>
<input type="text" name="email" ng-model="newcontact.email"/>
<label>Phone</label>
<input type="text" name="phone" ng-model="newcontact.phone"/>
<br/>
<input type="hidden" ng-model="newcontact.id" />

<input type="button" value="Save" ng-click="saveContact()" />


</form>
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="contact in contacts">
<td>{{ contact.name }}</td>
<td>{{ contact.email }}</td>
<td>{{ contact.phone }}</td>
<td>
<a href="#" ng-click="edit(contact.id)">edit</a> |
<a href="#" ng-click="delete(contact.id)">delete</a>
</td>
</tr>
</tbody>
</table>
</div>
<script>
var uid = 1;
function ContactController($scope) {
$scope.contacts = [
{ id:0, 'name': 'mmcc',
'email':'[email protected]',
'phone': '24323605'
}
];
$scope.saveContact = function() {
if($scope.newcontact.id == null) {
//if this is new contact, add it in contacts array
$scope.newcontact.id = uid++;
$scope.contacts.push($scope.newcontact);
} else {
//for existing contact, find this contact using id
//and update it.
for(i in $scope.contacts) {
if($scope.contacts[i].id == $scope.newcontact.id) {
$scope.contacts[i] = $scope.newcontact;
}
}

}
//clear the add contact form
$scope.newcontact = {};
}
$scope.delete = function(id) {
//search contact with given id and delete it
for(i in $scope.contacts) {
if($scope.contacts[i].id == id) {
$scope.contacts.splice(i,1);
$scope.newcontact = {};
}
}
}
$scope.edit = function(id) {
//search contact with given id and update it
for(i in $scope.contacts) {
if($scope.contacts[i].id == id) {
//we use angular.copy() method to create
//copy of original object
$scope.newcontact = angular.copy($scope.contacts[i]);
}
}
}
}
</script>
</body>
</html>

Output:

First thing to note, we created a variable uid and set its initial value to 1. This
variable is used to generate unique ids for each new contact we save. In real life
application you may want to do this at backend.
We defined one controller ContactController. This controller defines following
objects within $scope:

You might also like