Vous êtes sur la page 1sur 89

Agenda

1. Introduction to Angular JS 1.3 and Angular JS


2.0
2. MVC architecture in AngularJS (views, controller,
services)
3. Dependency Injection
4. Using Directives and Data Binding
5. Iterating with the ng-repeat Directive
6. Using Filters
7. Scope and Routes
8. Debugging Angular JS with Batarang plug-in
9. Web service using AngularJS (resource, http &
promise)
10.Angular UI bootstrap
11.Ng-grid
12.Localisation with Angular JS
13.Security in Angular JS <
Architecture
HTML + Java Script +
CSS 3 /Bootstrap MVC 5
Web API
Google Chrome V8 JS
REST
engine
http
OWIN (s)
middlewa serve
re r
Web SQLServer
HTTP (s) / Sockets socke
MongoDB
t

IIS 7.5/ 8.0 / Cloud


Angular JS server
Ext JS
Node JS
Backbone JS Google V8 java script
JQuery Engine
History
1995: JavaScript
2000: XMLHttpRequest
2006: jQuery (Library)
2009: Angular JS (Framework)
2010: Backbone JS
Other Client Side MVC frameworks:
Ext JS, can JS

With libraries, your code decides when to call a


particular function from a library. With frameworks, you
implement callbacks, and the framework calls you when
Angular Framework
At loading time, Angular turns DOM tree and
javascript into an angular app.

The HTML with Angular directives and filters are


compiled into a tree of views, the corresponding
scopes and controllers get attached to them,
and internal application loop ensures data
binding between the view and the model.

This is MVC with very clean separation between


view, controller and model.
Java script libraries
Jquery for DOM Manipulration and Ajax
calls
Require.js for loading script modules
dynamically
Underscore.js , Handlebar.js, Mustache.js, Jade
for working with Templates
Knockout.js for 2 way data binding (from
Microsoft)
Ext JS for creating SPA with MVC /
MVVM
Boilerplate.js for integrating all JS libraries
Why angular JS?
3 reasons to learn Angular JS :
1. It Was Developed by Google
2. It's Comprehensive
1. REST easy
2. MVVM to the rescue
3. Data binding and dependency injection
4. Extends HTML
5. Makes HTML your template
6. Enterprise level testing (qunit,
jasmine,mocha)
Angular JS
Use AngularJS if:

Responsive design is a requirement for your


application.
automated testing is a part of your
development culture.
Your team is comfortable with CSS and dealing
with cross-browser compatibility issues.
You want to confirm to application architecture
with MVC and MVVM design pattern.
Modular approach with Dependency injection
for loosely coupled architecture is required.
You want to extend HTML
Angular JS
Developed in 2009 by highly talented Google
engineers Miko Hevery and Adam Abrons,
AngularJS is asuperheroic JavaScript MVC /
MVVM framework for dynamic web apps
which enables to use HTML template language
and allows to extend HTML vocabulary to
express applications components in a clear,
concise manner to develop next generation
web applications.
What is Angular JS
AngularJS is a client-side MVC framework
written in JavaScript.

A JavaScript framework /Library for creating


dynamic SPA based web applications .
(30kb- minified)
What is Angular JS

AngularJS is a MVC framework and powerful


library that enhances HTML by attaching
directives to html pages with new attributes
or tags and expressions in order to define
very powerful templates directly. (Extending
HTML)

Declare dynamic views in web-


applications( SPA)

Extend HTML vocabulary for web


application.
Why Angular JS
Magical two way data binding
Structure front end code -MVC (solid and
testable code)
Routing support ( State based and View based)
SPA
Templating done with HTML 5
Enhanced User Experience with form
validation
Teach HTML new syntax with directives ( say
HTML 6)
Embeddable, testable (Jasmine) and injectable
(DI)
Embeddable Angular with Require JS /
Angular JS
Angular JS a Javascript MVC framework created
by Google to build properly architectured and
maintainable web applications.

It extends HTML into a more expressive and


readable format using Directives

It decreases emphasis on directly handling


DOM manipulation from the application logic
(JqLite)

Makes testing easy with unit testing tools like


Jasmine (Test Driven Developement)
What is Angular JS ?

Open Source with built in jQLite (Jquery)


GitHub: https://
github.com/angular/angular.js

Download library from


http://angularjs.org
IDE for Angular JS
1. Textmate

2. Sublime Text

3. Aptana studio 3.0

4. Eclipse

5. Visual Studio 2012/2013 (for .Net

Developers)

6. Jetbrains Webstorm
Tools for Angular JS
Batarang stable
(search for : batarang chrome extension for
angular)

Batarang is a Chrome developer tool extension


for inspecting the AngularJS web applications.

Batarang is for visualizing and examining the


runtime characteristics of AngularJS
applications (model / scope)

Plunker and jsFiddle


Both Plunker (http://plnkr.co) and jsFiddle
(http://jsfiddle.net) make it very easy to share
Tools for Angular JS
The Angular Seed project

Provides a good skeleton structure for AngularJS


apps to quickly bootstrap the app and start
developing.

It provides pre-configured test environment, a


set of useful scripts, and a readyto-use web
server.

https://github.com/angular/angular-seed

Download Zip and extract the zip to get a folder


called angular-seed-master.
Folder Structure of Angular JS
Angular JS - SPA
Angular JS Ingredients
Directives
Filters
Data Binding
Views
Controllers
Scope
Transclusion
Factory
Service
Providers
Routing
Config
Module
Dependency Injection
MVC with Angular JS
Model - View Controller
POJOs
(Plain Old JavaScript
Model Objects).
The data
JavaScrip
t
Controller
The behavior (Business Logic)
Modifying / updating the models

View
HTML
The interface
How the data is presented to the user
Model - View Controller
MVC is design pattern implemented in Angular JS for
Separation of concern ,Reusability, Maintainability ,
Testability and Extensibility
One way Data Binding
Angular JS - Two way data binding
Expressions
{{ }}
Angular expressions
Like JavaScript expressions except:
Evaluated in the current scope
No control statements: conditionals,
loops
Insert model values directly into the view

The interpolation directive is the most


fundamental directive that deals with model data
display.

<span>{{expression}}</span>
Expressions
Directives
Teach new tricks to HTML

During DOM compilation directives are


matched against the HTML and executed for
directives to register behavior, or transform
the DOM.

Angular has built-in directives (ng-app.)

Directives can be extended such that HTML


can be turned into a declarative domain
specific language (DSL).

ng is angular directive
Angular Directives
Make use of special ng attributes
(directives) on the HTML elements (ng
means Angular Directive)

ng-app
Determines which part of the page will use
AngularJS
If given a value it will load that application
module

ng-controller
Determines which Javascript Controller should
be used for that part of the page

ng-model
Determines what model the value of an input
Angular JS API Reference

Goto http://angularjs.org Develop API


reference
Angular JS API Reference

The data prefix (data-ng-app) is


very convenient for keeping HTML
documents HTML5- compliant, and
making them pass HTML5
validators tests.
Angular JS API Reference
Directives

data-ng-app=

data-ng-
model=
data-ng-view =

Scope

What ng-model does is


behind the scenes adding a
First Demo property in the memory called
name into whats called the
Two way Data Binding
Data binding is the automatic synchronization of
data between view and the model.

<body ng-init=name='AngularJS'">
<input type="text" ng-model="name"/>
<div><h2>Hello, {{name}}</div>
Modules
In AngularJS, applications are structured
inmodules

Module is a container for Controllers,


Factory, Services, Directives and Filters.

A module can depend on other modules.


(Module Dependency)

AngularJS splits module's lifecycle into


two phases:
The configuration phase: It is the phase
where all the recipes are collected and
configured
Modules
angular.module() is like global API for
creating or retrieving modules and registering
components.

The call to angular.module() returns a


reference to the newly created module.

angular.module('firstModule',[]);
//defines a module with no dependencies

angular.module('firstModule',
['moduleA','moduleB']);
//defines a module with 2 dependencies
Controller

The task of a controller is to augment the


scope by attaching models and functions to it
that are subsequently accessed in the view.

A controller is nothing but a constructor


function which is instantiated by AngularJS
when it encounters
ng-controller directive in HTML.
Angular JS Loosely coupled

Dependency
Injection
Modules
Attaching controller to Module:
You can attach Factory, Service,s Directives and
Filters
var firstModule=angular.module('firstModule',
[]);

firstModule.controller
(MyController',function($scope){
// register a controller
. });
firstModule.directive('FirstDirective',function(){
// register a directive
return { ..
Flaw: It };
is added to JavaScript global
}); scopeand it's not good practice to
Modules
What controller should not do:

No DOM manipulation. This should be done


in
directives.

Don't format model values in controllers.


Filters exist for this purpose.

Don't write repeatable code in controllers.


Rather
encapsulate them in factory / services.

What controller should do : (eg:


Modules
(function() { // Closure sets local scope
var firstModule =
angular.module('firstModule', []);
//firstModule is not global here
firstModule.controller('FirstController',
function($scope) {
// register a controller
});
firstModule.directive('FirstDirective', function()
{
// register a directive
return { ..
Immediately
}; Executed Function IEF
});executes as soon as it is created
Modules
Best Solution :

angular.module('firstModule',[])
.controller('FirstController ,function($scope){

})
.directive('FirstDirective',function(){
//your directive
return {
};
});
Modules strcuture
Modules strcuture

DEMO
Modules

Defined to use
routes

For data
access logic
(CRUD)
uses
factories /
services/
providers.
Application Flow in Angular JS
Application Flow in Angular JS
Application Flow
After the browser loads the HTML and parses
it into a DOM, the angular.js script file is
loaded.

Angular waits for the browser to fire the


DOMContentLoaded event. This is similar to
the way jQuery is bootstrapped

$(document).ready(function(){
// do jQuery
})
Application Flow
In the Angular.js file, towards the end, after
the entire code has been parsed by the
browser, you will find the following code:

jqLite(document).ready(function() {
angularInit(document, bootstrap);
});

This code calls ng-app directive in HTML tag


Application Flow
The module specification is optional and can
tell the $injector service which of the defined
modules to load.

//index.html
<!doctype html>
<html ng-app="tempApp">
<head>
...
// app.js
..
angular.module('tempApp', ['serviceModule'])
..
Application Flow
In turn, the $injector service will create
$rootscope, the parent scope of all Angular
scopes

This $rootscope is linked to DOM itself as a


parent to all other Angular scopes.

The $injector service will also create the


$compile service that will traverse the DOM and
look for directives.

These directives are searched for within the


complete list of declared Angular internal
directives and custom directives to recognize
Directives
Directives
A directive is something that attaches special
behavior to a DOMelement and teaches it
awesome tricks!

Directive Flavours:
E

M
Directives
ng-repeat: used to instantiate the template for
each item in the source collection received from
the scope of the controller.

ng-click: executes the action method form the


controller class when the element on the View is
clicked.

ng-class:This directive allows class attributes to


load dynamically.

ngIf:This basic if statement directive is used to


re-insert or eliminate an element from the DOM,
depending on whether the condition is true or
false.
Custom Directives
angular.module('myApp', [])

.directive('helloWorld', function() {
return {
restrict: 'AEC',
replace: true,
template: '<h3>Hello, World!</h3>'
};
});
Custom Directives
use camelCase to name the directive, when
using it in the
HTML , separate the words with dashes (-) or
colons (:) (Snake case):
<hello-world/> or <div hello-world />
Or:
<hello:world/>

To make it HTML 5 compliant :

<div data-hello-world></div>
Or:
<div x-hello-world></div>
Configuration Options
restrict: This provides a way to specify how a
directive should be used in HTML

'A'- only matches attribute name


'E'- only matches element name
'C'- only matches class name

These restrictions can all be combined as


needed:

'AEC'- matches either attribute or element or


class name
Configuration Options
template This specifies the HTML markup
that'll be produced when the directive is
processed by AngularJS.

The template can involve other directives,


expressions
({{ }}), etc.

We can Use templateUrl property instead of


template.
angular.module('myApp', [])
.directive('helloWorld', function() {
return {
restrict: 'AEC',
Configuration Options
elem: This is the element on which our
directive is applied.

This element is already jQLite wrapped. jQLite


is a subset of jQuery and supports the basic
DOM operations.

attrs: This is a map containing the attributes


and their values that are applied to the
directive in HTML
Configuration Options
replace specifies the generated template will
replace the HTML element on which the
directive is applied.

link - function used to set models on the


scope object,
watch models for changes, and add event
listeners to DOM elements.

scope: The scope object for the directive. By


default this is same as the parent's scope. For
instance, if you have ng-controller in the
markup and our directive is used insideDEMOit,
then the directive will use the parent
Configuration Options
The compile function is used to perform a
DOM transformation before the link function
runs.

The compile function accepts the following


arguments.

tElement The element on which the


directive is applied. The prefix t indicates that
this is a template element and no scope is
available yet.

attrs The map of attributes declared on


the element in markup.
Compilation of directive
When the application bootstraps, AngularJS
starts parsing the DOM using the $compile
service.

This searches for directives in the markup and


matches them against registered directives.

Once all of these have been identified,


AngularJS executes their compile functions.

The compile function returns a link function,


which is added to the list of link functions to
be executed
later. This is called the compile phase.
Configuration Options
angular.module('testModule')
.directive('testDirective', function() {
return {
compile: function(tElem,attrs) {
//do optional DOM transformation here
//tElem is jQLite/jQuery wrapped
return function(scope,elem,attrs) {
//linking function here
};
}
};
});
Changing a Directives Scope
By default, a directive gets its parent's scope.

If we're exposing the parent controller's scope


to the directives, they're free to modify its
properties.

To overcome this, isolated scope can be


created for internal use only.

Use a child scope This scope prototypically


inherits the parent's scope.

Use an isolated scope A new scope that


doesn't inherit from the parent and exists on its
Child vs Isolated scope
Child scope Isolated
scope
Directives
By extending and customizing how the browser
behaves with regard to the HTML, directives let
the application developer, or designer, focus
attention on what the application should do in
a declarative manner, rather than on
programming low level interactions with the
DOM.
$digest
In AngularJS terminology the process of
detecting model changes is called $digest loop
(or $digest cycle).

This method is invoked as part of the $apply


call and it will
evaluate all the watches registered on all the
scopes.
Controller in Directive
Interdirective communication :

The controller function of a directive is used if


you want to allow other directives to
communicate with yours.

In some cases you may need to create a


particular UI
component by combining two directives.
Transclusion
Transclusion is a feature that enables to
wrap a directive around arbitrary content.

We can extract and compile it against the


correct scope later, and eventually place it at
the specified position in the directive
template.

If you set transclude:true in the directive


definition, a new transcluded scope will be
created which prototypically
inherits from the parent scope.
Transclusion
Use ng-Transcludedirective

DEMO
Dependency Injection - DIP
Dependency Injection
The DI framework's in charge of creating
components, resolving their dependencies, and
passing them to other components when
requested.

Components may obtain their dependencies in


the following two ways:

1. By invoking new on a constructor function to


obtain their dependency themselves.

2. By using a global variable to look up


dependencies.
Dependency Injection
AngularJS does things in a different way:
using a service locator.

function SimpleController($scope,$rootScope,
$http){
$scope.someModel="Hello, World!";
}
The controller declares its dependencies through
the method parameters.

While instantiating the controller, AngularJS


looks for the registered services that match the
parameter names and automatically injects
them as arguments.
Dependency Injection
DI subsystem inject dependencies.

We call these dependencies "injectable types"


because they can be injected into other
components.

This improves reusability, extensibility and


testability with loose coupling among the
components.
Dependency Injection
The Provider ($provide)

The$provideservice is responsible for telling Angular


how to create new injectable types calledservices.

$provideservice injected into an


application'sconfigfunction which provides
dependency injection. (eg: Greeting service below)

app.config(function($provide) {
$provide.provider($GreetService', function() {
this.$get = function() {
return function(name) {
alert("Hello, " + name); }; };
}); });
Dependency Injection
In previous code, new provider for a service
calledgreeting inject a variable named
$GreetingService into any injectable function
and Angular will call the
provider's$getfunction in order to return a
new instance of the service.

app.controller('MainController',
function($scope, $GreetService) {
$scope.onClick = function()
{ $GreetService(Murthy'); };});
Dependency Injection
Factory,service, andvalueare all just
shortcuts to define a provider.

app.config(function($provide) {
$provide.factory('alertService',function(){
return function(){
alert('Service in Action');
}
});
});

Or we can call the method factory() on


angular.module()
Dependency Injection
function TestController($scope,
$http,customService){
//controller code goes here
}
When this controller is to be instantiated, the
$injector's instantiate method gets called.

$injector.instantiate(TestController);

While instantiating this controller $injector will


go through the parameters list and call
$injector.get(serviceName) to obtain the
service instance.
Dependency Injection
The injector is responsible for actually creating
instances of services using the code we
provided via$provide

Each AngularJS application has a


single$injector that gets created when the
application first starts.

$injector gets the instance of a defined service


by callinggeton it with the name of the
service.

var greeting = $injector.get($GreetFactory');


greeting(Murthy');
Dependency Injection
AngularJS creates an $injector for app while
bootstrapping.

angular.module('myApp')
.service('customService',function($injector){
var $http=$injector.get('$http'); //get $http
service
var $rootScope=$injector.get('$rootScope');
});
Animation - ng-animate
Ng-model Data Binding
The directivenganimate need to be declared
for theng-animateattribute to an element
that have another directive that changes the
DOM.

Directive Animation Type

ngRepeat enter, leave and move

ngView enter and leave

ngInclude enter and leave


Ng-model Data Binding
<div ng-repeat="item in items"
ng-animate=" 'animate' ">
...
</div>

<div ng-repeat="item in items"


ng-animate="{enter: 'animate-enter', leave:
'animate-leave'}">
...
</div>

Style classes :
For Enter: .animate-enter
For Leave: .animate-leave
Ng-model Data Binding
CSS Transition

To define a class with a CSS3 Transition, first set


thetransitionproperty and the initial element
state at the setupclass. Then, just set the final
state at theactiveclass.

.animate-enter {
-webkit-transition: 1s linear all; /* Chrome */
transition: 1s linear all;
opacity: 0;
}

.animate-enter.animate-enter-active {
opacity: 1;
Animation site - Plunker
http://
www.nganimate.org/angularjs/ng-repeat/spi
nning-keyframes-animation

Samples :
Move
3D Cube
3D Rotate
Scale
Appear
Skew
Yo Yo
Spinning
Angular JS charts
http://codepen.io/brunoscopelliti/pen/zIstF
(capital i)
Above site contain code for creating charts with
angular
Best Practice
Best Practice File Organization
Best Practice File Naming
Best Practice Angular

Vous aimerez peut-être aussi