Angular JS
Angular JS
206
AngularJS Essentials
What is AngularJS?
AngularJS Building Blocks
Setting up the Environment
AngularJS Bootstrap
Modules
Controllers...and more!
By Gil Fink
W h at is A n g u l a r J S?
AngularJS is a very popular MVW (Model/View/Whatever)
framework which is maintained by Google. AngularJS enables
web developers to impose MVC structure on their client-side
code and to build dynamic web applications easily.
AngularJS introduces component-based architecture. It also
includes a variety of conventions that developers should know
and use that will be presented in this Refcard. AngularJS
includes a wide range of features that help to build Single Page
Applications (SPAs) faster and is considered a one stop shop
for creating SPAs.
Lets explore how some of these parts relate to the MVC design
pattern:
A n g u l a r J S B u i l di n g B lo c k s
The Model
angular
js essentials
Java Enterprise
Edition 7
Modules
Im plem entations
Controllers
Scopes
Views
Templates
Services
Filters
Directives
Routing
Dependency
Injection
The model is the data structure that holds some business data.
It will usually reside from the server side using a REST API or
from a service. The model is exposed to the AngularJS view
using the $scope object.
The View
The HTML part that presents the data structure and enables
user interactions. The view binds to a model using the $scope
object. It can call controller functions through the $scope
object as well. It uses filters to transform the model data to an
appropriate representation. It also uses directives as reusable
web components and for DOM manipulation.
D Z o ne, Inc.
dz o ne.c o m
2
The Controller
angular js essentials
S e tti n g u p t h e E n vi ro n m e n t
The first thing that you want to do is to setup the environment.
AngularJS can be downloaded from www.angularjs.org and
included in your web page or it can be included directly from Google
Content Delivery Network (CDN):
Manual Bootstrap
<script src=https://ajax.googleapis.com/ajax/libs/
angularjs/1.2.9/angular.min.js></script>
angular.element(document).ready(function() {
angular.module(myApp, []);
angular.bootstrap(document, [myApp]);
});
In the previous code you can see the use of AngularJSs ready
function, which will wire an event handler to the Dom Content
Loaded event underneath. Later on we (can/will) create a module
with the name myApp and bootstrap the DOM with the module.
This of course brings us the question what is an AngularJS
module?
<!doctype html>
<html ng-app=myApp>
<head>
<script src=https://ajax.googleapis.com/ajax/libs/
angularjs/1.2.9/angular.min.js></script>
</head>
<body>
<div>
</div>
</body>
</html>
modules
What is a Module?
A n g u l a r J S B o o tst r a p
D Z o ne, Inc .
angular.module(myApp, [storageService]);
Configuring a Module
You can add module configuration using the config function once
you declare a module. The configuration will get executed when the
module is loading. You can inject providers or constants (which will
be discussed later in the refcard) to the configuration block you are
writing. Here is an example of a call for the config function:
dz o ne .c o m
angular js essentials
Co n t ro l l e r s
angular.module(myApp, [storageService])
.config(function ($provide, $filterProvider) {
$provide.value(myValue, 1);
$filterProvider.register(myFilter, ...);
});
What is a Controller?
Creating a Controller
angular.module(myApp, [storageService])
.run(function (someInstance) {
someInstance.doSomething();
});
<div ng-controller=MyController>
</div>
Once you are familiar with controllers lets talk about scopes.
s co p e s
What is a scope?
Scopes are objects that include properties and the functions set by
controllers that a view can later use. You can think about scopes as
the glue between a controller and a single view.
Once a controller is attached to a view using the ng-controller
directive, all the scope properties and functions are data bound
to the view and it can use them. Changes to scope properties are
reflected in the bounded view, and user interactions can also
change the bound properties.
dz o ne .c o m
angular js essentials
You can also put inside scope properties full model objects that later
can be used by a view.
V i e ws
Views are a dynamic HTML that present the models and interact
with the user. AngularJS views can be bound to a controller using
the ng-controller directive. Once a binding is set, you can use scope
properties and functions in the view. In order to harness the full
potential of views you should understand two AngularJS concepts
which relate to views: templates and expressions.
Service
Type
Description
value
factory
service
provider
templates
When you want to use the previous services you will inject them to
a dependent object by their name and use them. For example, here
is a controller that uses the previous services:
Expressions
In the previous template example you could see that we used curly
brackets to wrap btnText. This is an example of an expression.
Expressions are JavaScript code that is used for binding.
Expressions are placed in double curly brackets {{}}. When
AngularJS processes a template, it searches for expressions and
it parses them and evaluates them. The evaluation of expressions
is being done against the controller scope object. If the scope
doesnt contain the expression value, AngularJS will not throw an
exception. This behavior enables you to perform lazy binding.
myApp.controller(myController, function($scope,
myValue, myFactory) {
$scope.value = myValue;
$scope.greet = myFactory;
});
Built-in
Service
$http
You can also use expressions for one time binding. Any expression
that starts with :: will evaluate only once. The following code
example shows you how to use one time binding on a message
property:
$resource
$q
$log
S e rvi c e s
$location
What is a Service?
D Z o ne, Inc .
Description
dz o ne .c o m
F i lt e r s
What is a Filter?
{{ message | filter }}
You can create your custom filters in two ways: using the modules
filter function or registering a filter in the $filterProvider service.
The first argument that a filter receives in its callback function is
the input value. All the other arguments are considered additional
arguments, which can be used by the filter function.
The following example shows how to register a filter that turns any
string to its upper case representation:
Directive
Configur ation
restrict
template
AngularJS comes with a set of built-in filters that you can use. Here
are their descriptions:
Built-in
Filters
currency
date
number
json
replace
Description
templateUrl
lowercase
uppercase
limitTo
orderBy
filter
angular js essentials
scope
transclude
D i r e c tiv e s
What is a Directive?
D Z o ne, Inc .
dz o ne .c o m
Description
When you want to use this directive you can write in your HTML:
required
<my-dialog></my-dialog>
or:
<div my-dialog></div>
Description
ngModel
ngEventName
(replace
EventName with
any DOM event)
angular js essentials
ngValue
ngBind
ngClass
ngInclude
ngRepeat
ngShow
ngSwitch
A required field
min
max
minlength
maxlength
pattern
Description
<form name=myForm>
<div>
<input type=text name=username ngmodel=user.name required/>
</div>
<div>
<input type=password name=password ngmodel=user.password required />
</div>
<button ng-click=login(user)>
Login
</button>
</form>
In this form, the scope will have a property with the name myForm
which will be bound to the form. The myForm property will include
the username and password sub-properties, which will include
references to the input types. If the username and password
wouldnt be supplied, the $error of the form will be set to an error
and the form wouldnt submit.
AngularJS also decorates form elements and input types with CSS
classes. You can use those classes to change the presented style
of an element according to its state. The CSS classes that you can
use are:
ng-valid
ng-invalid
ng-invalid-[validation name]
ng-pristine
ng-dirty
D Z o ne, Inc .
Ro u ti n g
One of the most important mechanisms in Single Page Applications
(SPA) is client-side routing. Client-side routing enables developers
dz o ne .c o m
7
to intercept route changes and, instead of rendering a new page in
the server, render a document fragment in the client and replace
a shell element. This is how you move from one page to another
in SPAs. AngularJS provides a routing feature that can be used
to create this behavior to inject views into an ngView-decorated
element.
angular js essentials
A dditi o n a l R e s o u rc e s
Description
template/
templateUrl
controller
redirectTo
forum/#!forum/angular
RECOMMENDED BOOK
BUY NOW
Communities:
Share links, author articles, and engage with other tech experts
JOIN NOW
DZone, Inc.
150 Preston Executive Dr.
Cary, NC 27513
DZone communities deliver over 6 million pages each month to more than 3.3 million software
developers, architects and decision makers. DZone offers something for everyone, including news,
tutorials, cheat sheets, research guides, feature articles, source code and more.
888.678.0399
919.678.0300
Refcardz Feedback Welcome
refcardz@dzone.com
dz oSponsorship
ne .c o m Opportunities
Copyright 2015 DZone, Inc. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted,
DZone,
D Z o ne, Inc
. in anyInc.
form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher.
sales@dzone.com
Version 1.0
$7.95