SlideShare une entreprise Scribd logo
1  sur  164
Télécharger pour lire hors ligne
Shaping Up with Angular
Level 1: Getting Started
What you need to know
Must know Not so important
Nice to know
Automated Testing
BDD - Behavior Driven Development
TDD - Test Driven Development
etc
HTML & CSS
JavaScript
jQuery
Ruby on Rails
Python, PHP, etc
Databases
Why Angular?
If you’re using JavaScript to create a dynamic website,
Angular is a good choice.
• Angular helps you organize your JavaScript
• Angular helps create responsive (as in fast) websites.
• Angular plays well with jQuery
• Angular is easy to test
Traditional Page-Refresh
Screencast: Request-Response Application
NOTE: Time between user 

interaction and response.
Web Server
HTML JavaScript
Response with Webpage & Assets
Web Browser
URL Request to server
Response with Webpage & Assets
User clicks on link, new Request HTML JavaScript
Browser loads up
entire webpage.
Browser loads up
entire webpage.
Screencast: Request-Response Application
NOTE: Note how responsive the page is
A “responsive” website using Angular
Web Server
Response with Webpage & Assets
Web Browser
URL Request to server
Response with JSON Data
User clicks on link, new Request
HTML JavaScript
DATA
Browser loads up
entire webpage.
Data is loaded into
existing page.
Modern API-Driven Application
HTML Browser
App
Data
Source
Mobile
App
Developers
Server
API
A client-side JavaScript Framework for adding interactivity to HTML.
app.jsindex.html
How do we tell our HTML when to trigger our JavaScript?
<!DOCTYPE html>

<html>

<body

. . .
</body>

</html>
function Store

alert('Welcome, Gregg!');

}

(){
>
What is Angular JS?
<!DOCTYPE html>

<html>

<body

. . .
</body>

</html>
app.js
function Store

alert('Welcome, Gregg!');

}

A Directive is a marker on a HTML tag that tells Angular to run or reference
some JavaScript code.
Directives
Name of
function to callindex.html
Controller(){
ng-controller="StoreController">
The Flatlanders Store!
Screencast: Flatlanders Store
Fully Functional
Download AngularJS http://angularjs.org/
We’ll need angular.min.js
Downloading the libraries
Download Twitter Bootstrap http://getbootstrap.com/
We’ll need bootstrap.min.css
<!DOCTYPE html>

<html>

<head>

<link rel="stylesheet" type="text/css" href="bootstrap.min.css" />

</head>

<body>

<script type="text/javascript" src="angular.min.js"></script>

</body>

</html>
Getting Started
index.html
Twitter Bootstrap
AngularJS
Modules
• Where we write pieces of our Angular application.
• Makes our code more maintainable, testable, and readable.
• Where we define dependencies for our app.
Modules can use other Modules...
Creating Our First Module
Dependencies
Other libraries we might need. 

We have none... for now…
Application
Name
AngularJS
var app = angular.module('store', [ ]);
Including Our Module
var app = angular.module('store', [ ]); app.js
index.html
<!DOCTYPE html>

<html>

<head>

<link rel="stylesheet" type="text/css" href="bootstrap.min.css" />

</head>

<body>

<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="app.js"></script>
</body>

</html>
Including Our Module
var app = angular.module('store', [ ]); app.js
<!DOCTYPE html>

<html ng-app="store">

<head>

<link rel="stylesheet" type="text/css" href="bootstrap.min.css" />

</head>

<body>

<script type="text/javascript" src="angular.min.js"></script>

<script type="text/javascript" src="app.js"></script>

</body>

</html>
Run this module
when the document
loads.
index.html
Allow you to insert dynamic values into your HTML.
Expressions
Numerical Operations
evaluates to
String Operations
evaluates to
+ More Operations:
http://docs.angularjs.org/guide/expression
<p>

I am {{4 + 6}}

</p>
<p>

{{"hello" + " you"}}

</p>
<p>

I am 10

</p>
<p>

hello you

</p>

Including Our Module
var app = angular.module('store', [ ]); app.js
<!DOCTYPE html>

<html ng-app="store">

<head>

<link rel="stylesheet" type="text/css" href="bootstrap.min.css" />

</head>

<body>

<script type="text/javascript" src="angular.min.js"></script>

<script type="text/javascript" src="app.js"></script>

<p>{{"hello" + " you"}}</p>
</body>

</html> index.html
Challenges
Working With Data
...just a simple
object we want to
print to the page.
var gem = {

name: 'Dodecahedron',

price: 2.95,

description: '. . .',

}.
Controllers
app.js
Notice that controller is attached to (inside) our app.
Controllers are where we define our app’s behavior by defining
functions and values.
Wrapping your Javascript
in a closure is a good habit!
var gem = {

name: 'Dodecahedron',

price: 2.95,

description: '. . .',

}.
})();
(function(){

var app = angular.module('store', [ ]);
app.controller('StoreController', function(){



});
Storing Data Inside the Controller
app.js
Now how do we
print out this
data inside our
webpage?
this.product = gem;
var gem = {

name: 'Dodecahedron',

price: 2.95,

description: '. . .',

}.
})();
(function(){

var app = angular.module('store', [ ]);
app.controller('StoreController', function(){



});
<!DOCTYPE html>

<html ng-app="store">

<head>

<link rel="stylesheet" type="text/css" href="bootstrap.min.css" />

</head>

!
!
!
!
!
!
!
!
</html>

<body>

<div>

<h1> Product Name </h1>

<h2> $Product Price </h2>

<p> Product Description </p>

</div>

<script type="text/javascript" src="angular.min.js"></script>

<script type="text/javascript" src="app.js"></script>

</body>
Our Current HTML
Let’s load our data into
this part of the page.
}
index.html
<body>

<div>

<h1> Product Name </h1>

<h2> $Product Price </h2>

<p> Product Description </p>

</div>

<script type="text/javascript" src="angular.min.js"></script>

<script type="text/javascript" src="app.js"></script>

</body>
(function(){

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



app.controller('StoreController', function(){

this.product = gem;
});
. . .
})(); app.js
index.html
Attaching the Controller
<body>

<div ng-controller="StoreController as store">

<h1> Product Name </h1>

<h2> $Product Price </h2>

<p> Product Description </p>

</div>

<script type="text/javascript" src="angular.min.js"></script>

<script type="text/javascript" src="app.js"></script>

</body>
Attaching the Controller
(function(){

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



app.controller('StoreController', function(){

this.product = gem;
});
. . .
})(); app.js
index.html
Controller name AliasDirective
<body>

<div ng-controller="StoreController as store">

!
!
</div>

<script type="text/javascript" src="angular.min.js"></script>

<script type="text/javascript" src="app.js"></script>

</body> index.html
Displaying Our First Product
(function(){

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



app.controller('StoreController', function(){

this.product = gem;
});
. . .
})(); app.js
<h1> {{store.product.name}} </h1>

<h2> ${{store.product.price}} </h2>

<p> {{store.product.description}} </p>
Understanding Scope
Would never print a
value!
The scope of
the Controller
is only inside
here...
}{{store.product.name}}
<h1> {{store.product.name}} </h1>

<h2> ${{store.product.price}} </h2>

<p> {{store.product.description}} </p>
<body>

<div ng-controller="StoreController as store">

!
!
</div>

<script type="text/javascript" src="angular.min.js"></script>

<script type="text/javascript" src="app.js"></script>

</body>
Challenges
</div>

<script type="text/javascript" src="angular.min.js"></script>

<script type="text/javascript" src="app.js"></script>

</body>
<body ng-controller="StoreController as store">

<div>

<h1> {{store.product.name}} </h1>

<h2> ${{store.product.price}} </h2>

<p> {{store.product.description}} </p>
Adding A Button
index.html
var gem = {

name: 'Dodecahedron',

price: 2.95,

description: '. . .',
}.
var gem = {

name: 'Dodecahedron',

price: 2.95,

description: '. . .',
}.
canPurchase: false
</div>

<script type="text/javascript" src="angular.min.js"></script>

<script type="text/javascript" src="app.js"></script>

</body>
Adding A Button
index.html
<button
How can we
only show
this button...
...when this is true?
Directives tothe rescue!
<body ng-controller="StoreController as store">

<div>

<h1> {{store.product.name}} </h1>

<h2> ${{store.product.price}} </h2>

<p> {{store.product.description}} </p>
> Add to Cart </button>
var gem = {

name: 'Dodecahedron',

price: 2.95,

description: '. . .',
}.
canPurchase: false
</div>

<script type="text/javascript" src="angular.min.js"></script>

<script type="text/javascript" src="app.js"></script>

</body>
NgShow Directive
index.html
<button
<body ng-controller="StoreController as store">

<div>

<h1> {{store.product.name}} </h1>

<h2> ${{store.product.price}} </h2>

<p> {{store.product.description}} </p>
ng-show="store.product.canPurchase"> Add to Cart </button>
Will only show the element if the
value of the Expression is
true.
</div>

<script type="text/javascript" src="angular.min.js"></script>

<script type="text/javascript" src="app.js"></script>

</body> index.html
<button
<body ng-controller="StoreController as store">

<div

<h1> {{store.product.name}} </h1>

<h2> ${{store.product.price}} </h2>

<p> {{store.product.description}} </p>
ng-show="store.product.canPurchase"> Add to Cart </button>
NgHide Directive
If the product is sold out
we want to hide it.
var gem = {

name: 'Dodecahedron',

price: 2.95,

description: '. . .',
}.
canPurchase: true,
soldOut: true
>
</div>

<script type="text/javascript" src="angular.min.js"></script>

<script type="text/javascript" src="app.js"></script>

</body> index.html
<button
<body ng-controller="StoreController as store">

<div

<h1> {{store.product.name}} </h1>

<h2> ${{store.product.price}} </h2>

<p> {{store.product.description}} </p>
ng-show="store.product.canPurchase"> Add to Cart </button>
NgHide Directive
If the product is sold out
we want to hide it.
This is awkward and
a good example to
use ng-hide!
var gem = {

name: 'Dodecahedron',

price: 2.95,

description: '. . .',
}.
canPurchase: true,
soldOut: true,
ng-show="!store.product.soldOut">
</div>

<script type="text/javascript" src="angular.min.js"></script>

<script type="text/javascript" src="app.js"></script>

</body> index.html
<button
<body ng-controller="StoreController as store">

<div

<h1> {{store.product.name}} </h1>

<h2> ${{store.product.price}} </h2>

<p> {{store.product.description}} </p>
ng-show="store.product.canPurchase"> Add to Cart </button>
NgHide Directive
If the product is sold out
we want to hide it.
Much better!
var gem = {

name: 'Dodecahedron',

price: 2.95,

description: '. . .',
}.
canPurchase: true,
soldOut: true,
ng-hide="store.product.soldOut">
Multiple Products
app.js
var gem = 

name: "Dodecahedron",

price: 2.95,

description: ". . .",

canPurchase: true,

},

{
app.controller('StoreController', function(){

this.product = gem

});

;
Multiple Products
app.js
var gems = [



name: "Dodecahedron",

price: 2.95,

description: ". . .",

canPurchase: true,

},

{

name: "Pentagonal Gem",

price: 5.95,

description: ". . .",

canPurchase: false,

}…

];
{
Now we have an array...
How might we display all these
products in our template?
Maybe a
Directive?
app.controller('StoreController', function(){

this.products = gems

});

;
So we have multiple products...
Working with An Array
index.html
<body ng-controller="StoreController as store">

<div>

<h1> {{store.products[0].name}} </h1>

<h2> ${{store.products[0].price}} </h2>

<p> {{store.products[0].description}} </p>

<button ng-show="store.products[0].canPurchase">

Add to Cart</button>

</div>

. . .

</body>
index.html
Working with An Array
. . .

</body>
Displaying the first product
is easy enough...
<body ng-controller="StoreController as store">

<div>

<h1> {{store.products[0].name}} </h1>

<h2> ${{store.products[0].price}} </h2>

<p> {{store.products[0].description}} </p>

<button ng-show="

Add to Cart</button>

</div>
store.products[0].canPurchase">
Working with An Array
index.html
<body ng-controller="StoreController as store">

<div

<h1> {{store.products[0].name}} </h1>

<h2> ${{store.products[0].price}} </h2>

<p> {{store.products[0].description}} </p>

<button ng-show="

Add to Cart</button>

</div>
. . .

</body>
<div>

<h1> {{store.products[1].name}} </h1>

<h2> ${{store.products[1].price}} </h2>

<p> {{store.products[1].description}} </p>

<button ng-show="store.products[1].canPurchase">

Add to Cart</button>

</div>
Why repeat yourself?
Why repeat yourself?
Why... You get it.
>
store.products[0].canPurchase">
That works...
Working with An Array
index.html
<body ng-controller="StoreController as store">

<div

<h1> {{product.name}} </h1>

<h2> ${{product.price}} </h2>

<p> {{product.description}} </p>

<button ng-show="

Add to Cart</button>

</div>
. . .

</body>
ng-repeat="product in store.products"
product
>
Repeat this
section for
each product.
}.canPurchase">
What We Have Learned So Far
Directives – HTML annotations that trigger Javascript behaviors
Modules – Where our application components live
Controllers – Where we add application behavior
Expressions – How values get displayed within the page
Challenges
Shaping Up with Angular.JS
Level 2: Filters, Directives, and Cleaner Code
ng-app – attach the Application Module to the page
Directives We Know & Love
ng-controller – attach a Controller function to the page
ng-show / ng-hide – display a section based on an Expression
ng-repeat – repeat a section for each item in an Array
<html ng-app="store">
<body ng-controller="StoreController as store">
<h1 ng-show="name"> Hello, {{name}}! </h1>
<li ng-repeat="product in store.products"> {{product.name}} </li>
Our Current Code
<body ng-controller="StoreController as store">

<ul class="list-group">

<li class="list-group-item" ng-repeat="product in store.products">

<h3> 

{{product.name}}
index.html
<em class="pull-right">${{product.price </em>}}
</h3>

</li>

</ul>

</body>
There’s a better way
to print out prices.
$2
Our First Filter
Pipe - “send the output into”
Format this into currency
Notice it gives the dollar sign (localized)
Specifies number of decimals
index.html
<em class="pull-right">{{product.price | currency </em>}}
<body ng-controller="StoreController as store">

<ul class="list-group">

<li class="list-group-item" ng-repeat="product in store.products">

<h3> 

{{product.name}}
</h3>

</li>

</ul>

</body>
$2.00
{{ data | filter:options }}
Formatting with Filters
*Our Recipe
{{'1388123412323' | date:'MM/dd/yyyy @ h:mma'}}
date
12/27/2013 @ 12:50AM
{{'octagon gem' | uppercase}}
uppercase & lowercase
OCTAGON GEM
{{'My Description' | limitTo:8}}
limitTo
My Descr
<li ng-repeat="product in store.products | orderBy:'-price'">
orderBy Will list products by descending price.
Without the - products would list in ascending order.
<li ng-repeat="product in store.products | limitTo:3">
* *
var gems = [

{ name: 'Dodecahedron Gem',
price: 2.95,

description: '. . .',

images: [

{
full: 'dodecahedron-01-full.jpg',
thumb: 'dodecahedron-01-thumb.jpg'

},

{
full: "dodecahedron-02-full.jpg",
. . .
Adding an Image Array to our Product Array
Our New Array
Image Object
To display the first image in a product: {{product.images[0].full}}
app.js
<body ng-controller="StoreController as store">

<ul class="list-group">

<li class="list-group-item" ng-repeat="product in store.products">

<h3> 

{{product.name}}
<em class="pull-right">{{product.price | currency}}</em>
<img ng-src="{{product.images[0].full}}"/>
</h3>

</li>

</ul>

</body> index.html
Using ng-src for Images
NG-SOURCE
to the rescue!
…the browser tries to load the image
before the Expression evaluates.
Using Angular Expressions inside a src attribute causes an error!
<img src="{{product.images[0].full}}"/>
Our Products with Images
Challenges
More With Directives
How can I make my application
more interactive?
A Simple Set of Tabs
index.html
<section>

<ul class="nav nav-pills”>
<li> <a href
<li> <a href
<li> <a href
>Description</a> </li>
>Specifications</a> </li>
>Reviews</a> </li>
</ul>
</section>
Introducing a new Directive!
index.html
Assigning a value to tab.
For now just print this value to the screen.
<section>

<ul class="nav nav-pills”>
<li> <a href
<li> <a href
<li> <a href
>Description</a> </li>
>Specifications</a> </li>
>Reviews</a> </li>
{{tab}}
ng-click="tab = 1"
ng-click="tab = 2"
ng-click="tab = 3"
</ul>
</section>
Introducing a new Directive!
When ng-click changes the value of tab …
… the {{tab}} expression automatically gets updated!
!
Expressions define a 2-way Data Binding ...
this means Expressions are re-evaluated when a property changes.
Whoa, it’s dynamic and stuff...
<div class="panel"
<div class="panel"
Let’s add the tab content panels
How do we make the tabs trigger the panel to show?
<h4>Description</h4>

<p>{{product.description}}</p>

</div>
<div class="panel"
<h4>Specifications</h4>

<blockquote>None yet</blockquote>

</div>
<h4>Reviews</h4>

<blockquote>None yet</blockquote>

</div>
>
>
>
tabs are up here...
. . .
Let’s add the tab content panels
Now when a tab is selected it will show the appropriate panel!
<div class="panel" >
>
>
<h4>Description</h4>

<p>{{product.description}}</p>

</div>
<h4>Specifications</h4>

<blockquote>None yet</blockquote>

</div>
<h4>Reviews</h4>

<blockquote>None yet</blockquote>

</div>
ng-show="tab === 1"
ng-show="tab === 2"
ng-show="tab === 3"<div class="panel"
<div class="panel"
show the panel
if tab is the
right number
But how do we set an
initial value for a tab?
Setting the Initial Value
index.html
ng-init allows us to evaluate an expression in the current scope.
<section ng-init="tab = 1">
<ul class="nav nav-pills">

<li> <a href ng-click="tab = 1">Description</a> </li>

<li> <a href ng-click="tab = 2">Specifications</a> </li>

<li> <a href ng-click="tab = 3">Reviews</a> </li>

</ul>
. . .
Now with the Initial Tab
Setting the Active Class
We need to set the class to active if current tab is selected ...
index.html
</ul>
ng-init="tab = 1">
<ul class="nav nav-pills”>
>Description</a>
>Specifications</a>
>Reviews</a>
ng-click="tab = 1"
ng-click="tab = 2"
ng-click="tab = 3"
<section
<li
<li
<li
>
>
>
<a href
<a href
<a href
</li>
</li>
</li>
The ng-class directive
Name of the class to set.
Expression to evaluate
If true, set class to “active”,
otherwise nothing.
index.html
ng-init="tab = 1"><section
<ul class="nav nav-pills”>
<li
<li
<li
ng-click="tab = 1"
ng-click="tab = 2"
ng-click="tab = 3"
>Description</a>
>Specifications</a>
>Reviews</a>
</li>
</li>
</li>
</ul>
. . .
>
>
>
ng-class="{ active:tab === 1 }"
ng-class="{ active:tab === 2 }"
ng-class="{ active:tab === 3 }"
<a href
<a href
<a href
Feels dirty, doesn’t it?
All our application’s logic is inside our HTML.
How might we pull this
logic into a Controller?
index.html
<section
<ul class="nav nav-pills">
<li >
<a href >Description</a>
<li
</li>
>
<a href >Specifications</a>
<li
</li>
>
<a href >Reviews</a>
</li>
</ul>
ng-click=" "tab = 1
"tab = 2ng-click="
ng-click=" "tab = 3
ng-class="{ active: }">tab === 1
ng-class="{ active: }">tab === 2
ng-class="{ active: }">tab === 3
<div class="panel" ng-show="
<h4>Description </h4>

<p>{{product.description}}</p>

</div>
…
tab === 1">
ng-init="tab = 1">
Creating our Panel Controller
index.html
app.js
ng-init="tab = 1"<section
<ul class="nav nav-pills">
<li >
<a href >Description</a>
<li
</li>
>
<a href >Specifications</a>
<li
</li>
>
<a href >Reviews</a>
</li>
</ul>
ng-controller="PanelController as panel"
app.controller("PanelController", function(){
});
ng-click=" "tab = 1
"tab = 2ng-click="
ng-click=" "tab = 3
<li ng-class="{ active: }">tab === 1
<li ng-class="{ active: }">tab === 2
<li ng-class="{ active: }">tab === 3
<div class="panel" ng-show="
<h4>Description </h4>

<p>{{product.description}}</p>

</div>
…
tab === 1">
>
Moving our tab initializer
index.html
app.js
<section
<ul class="nav nav-pills">
<li >
<a href >Description</a>
<li
</li>
>
<a href >Specifications</a>
<li
</li>
>
<a href >Reviews</a>
</li>
</ul>
app.controller("PanelController", function(){
});
this.tab = 1;
<a href ng-click=" "tab = 1
<a href ng-click=" "tab = 2
<a href ng-click=" "tab = 3
<li ng-class="{ active: }">tab === 1
<li ng-class="{ active: }">tab === 2
<li ng-class="{ active: }">tab === 3
<div class="panel" ng-show="
<h4>Description </h4>

<p>{{product.description}}</p>

</div>
…
tab === 1">
ng-controller="PanelController as panel" >
Creating our selectTab function
index.html
app.js
<section
<ul class="nav nav-pills">
ng-controller="PanelController as panel">
<li >
<a href ng-click="panel.selectTab(1) >Description</a>"
<li
</li>
>
<a href >Specifications</a>ng-click="panel.selectTab(2)"
</li>
<li >
<a href ng-click="panel.selectTab(3) >Reviews</a>
</li>
</ul>
"
app.controller("PanelController", function(){
});
this.tab = 1;
ng-class="{ active:
ng-class="{ active:
ng-class="{ active:
}">
}">
}">
tab === 1
tab === 2
tab === 3
<div class="panel" ng-show="
<h4>Description </h4>

<p>{{product.description}}</p>

</div>
…
tab === 1">
this.tab = setTab;
};
function(setTab) {this.selectTab =
Creating our isSelected function
index.html
app.js
<section
<ul class="nav nav-pills">
ng-controller="PanelController as panel">
<li ng-class="{ active:
ng-class="{ active:
ng-class="{ active:
panel.isSelected(1)
panel.isSelected(2)
panel.isSelected(3)
}">
}">
}">
<a href ng-click="panel.selectTab(1) >Description</a>"
<a href >Specifications</a>ng-click="panel.selectTab(2)"
<a href ng-click="panel.selectTab(3) >Reviews</a>"
</li>
</ul>
panel.isSelected(1)<div class="panel" ng-show=" ">
<h4>Description </h4>

<p>{{product.description}}</p>

</div>
…
</li>
<li
</li>
<li
<li
</li>
app.controller("PanelController", function(){
});
this.tab = 1;
this.isSelected = function(checkTab){
return this.tab === checkTab;
};
this.tab = setTab;
};
function(setTab) {this.selectTab =
Challenges
Shaping Up with Angular
Level 3: Forms, Models, and Validations
More Directives: Forms & Models
How can I let my users add content?
Adding reviews to our products
app.js
app.controller("StoreController", function(){

this.products = [

{ 

name: 'Awesome Multi-touch Keyboard', 

price: 250.00,

description: "...",

images: [...],

reviews: [

{ 

stars: 5,

body: "I love this product!",

author: "joe@thomas.com"

},

{ 

stars: 1,

body: "This product sucks",

author: "tim@hater.com"

}

. . .
<li class="list-group-item" ng-repeat="product in store.products">

. . .

<div class="panel" ng-show="panel.isSelected(3)">

<h4> Reviews </h4>



<blockquote ng-repeat="review in product.reviews">

<b>Stars: {{review.stars}}</b>

{{review.body}} 

<cite>by: {{review.author}}</cite> 

</blockquote>

</div>

Looping Over Reviews in our Tab
index.html
We’re displaying Reviews!
Nothing new here, but how do we start to implement forms?
<h4> Reviews </h4>



<blockquote ng-repeat="review in product.reviews">...</blockquote>
Writing out our Review Form
index.html
<form name="reviewForm">
<select
<option value="1">1 star</option>

<option value="2">2 stars</option>

. . .

</select>
<textarea></textarea>
<label>by:</label>
<input type="email" />
<input type="submit" value="Submit" />

</form>
>
With Live Preview,.
index.html
<blockquote>
<b>Stars: {{review.stars}}</b>

{{review.body}} 

<cite>by: {{review.author}}</cite> 

</blockquote>
How do we bind this review
object to the form?
<option value="1">1 star</option>

<option value="2">2 stars</option>

. . .

</select>
<textarea></textarea>
<label>by:</label>
<input type="email" />
<input type="submit" value="Submit" />

</form>
<select>
<form name="reviewForm">
Introducing ng-model&,
index.html
ng-model="review.stars"
ng-model="review.body"
ng-model="review.author"
<select >
<option value="1">1 star</option>

<option value="2">2 stars</option>

. . .

</select>
<textarea ></textarea>
<label>by:</label>
<input type="email" />
<input type="submit" value="Submit" />

</form>
<form name="reviewForm">
<blockquote>
<b>Stars: {{review.stars}}</b>

{{review.body}} 

<cite>by: {{review.author}}</cite> 

</blockquote>
ng-model binds the
form element value
to the property
Live Preview In Action
But how do we actually add the new review?
<input ng-model="review.terms" type="checkbox" /> I agree to the terms
Two More Binding Examples
With a Checkbox
With Radio Buttons
Sets value to true or false
Sets the proper value based on which is selected
What color would you like? 



<input ng-model="review.color" type="radio" value="red" /> Red 

<input ng-model="review.color" type="radio" value="blue" /> Blue 

<input ng-model="review.color" type="radio" value="green" /> Green

Challenges
We need to Initialize the Review
index.html
We could do ng-init, but
we’re better off
creating a controller.
<label>by:</label> 

<input ng-model="review.author" type="email" />

<input type="submit" value="Submit" />

</form>
<form name="reviewForm">
<b>Stars: {{review.stars}}</b>
{{review.body}}
<cite>by: {{review.author}}</cite>
</blockquote>
<blockquote>
<select ng-model="review.stars">
<option value="1">1 star</option>

<option value="2">2 stars</option>

. . .

</select>
<textarea ng-model="review.body"></textarea>
Creating the Review Controller&
app.js
Now we need to update
all the Expressions to use
this controller alias.
index.html
ng-controller="ReviewController as reviewCtrl"<form name="reviewForm" >
<b>Stars: {{review.stars}}</b>
{{review.body}}
<cite>by: {{review.author}}</cite>
</blockquote>
<select ng-model="review.stars">
<option value="1">1 star</option>

<option value="2">2 stars</option>

. . .

</select>
<textarea ng-model="review.body"></textarea>
<blockquote>
app.controller("ReviewController", function(){

this.review = {};
});
Using the reviewCtrl.review
app.js
index.html
ng-controller="ReviewController as reviewCtrl"
reviewCtrl.
reviewCtrl.
reviewCtrl.
reviewCtrl.
reviewCtrl.
<form name="reviewForm" >
<blockquote>
<b>Stars: {{ review.stars}}</b>
{{ review.body}}
<cite>by: {{ review.author}}</cite>
</blockquote>
<select ng-model=" review.stars">
<option value="1">1 star</option>

<option value="2">2 stars</option>

. . .

</select>
<textarea ng-model=" review.body"></textarea>
app.controller("ReviewController", function(){

this.review = {};
});
Using ng-submit to make the Form Work^
app.js
index.html
ng-submit="reviewCtrl.addReview(product)"
We need to define
this function.
ng-submit allows us to call a function when the form is submitted.
app.controller("ReviewController", function(){

this.review = {};
});
reviewCtrl.
reviewCtrl.
reviewCtrl.
ng-controller="ReviewController as reviewCtrl"<form name="reviewForm"
<blockquote>
<b>Stars: {{ review.stars}}</b>
{{ review.body}}
<cite>by: {{ review.author}}</cite>
</blockquote>
>
reviewCtrl.
app.js
index.html
ng-controller="ReviewController as reviewCtrl"
reviewCtrl.
reviewCtrl.
ng-submit="reviewCtrl.addReview(product)"
Push review onto this
product’s reviews array.
app.controller("ReviewController", function(){

this.review = {};
});
this.addReview = function(product) {
product.reviews.push(this.review);
};
<form name="reviewForm"
<blockquote>
<b>Stars: {{ review.stars}}</b>
{{ review.body}}
<cite>by: {{ review.author}}</cite>
</blockquote>
Using ng-submit to make the Form Work^
Now with Reviews!
Review gets added,
but the form still has
all previous values!
<form name="reviewForm" ng-controller="ReviewController as reviewCtrl"
ng-submit="reviewCtrl.addReview(product)">
<blockquote>
<b>Stars: {{reviewCtrl.review.stars}}</b>
{{reviewCtrl.review.body}}
<cite>by: {{reviewCtrl.review.author}}</cite>
</blockquote>
Resetting the Form on Submit
app.js
index.html
Clear out the review, so the form will reset.
app.controller("ReviewController", function(){

this.review = {};
});
this.addReview = function(product) {
product.reviews.push(this.review);
};
this.review = {};
This Time the Form Resets However, if we refresh,
the reviews get reset!

We’re not saving the
reviews anywhere yet...
Challenges
Turns out Angular has some great client side validations we can
use with our directives.
What about validations?
Our Old Form Code
index.html
<form name="reviewForm" ng-controller="ReviewController as reviewCtrl"
ng-submit="reviewCtrl.addReview(product)">
<select ng-model="reviewCtrl.review.stars"
<option value="1">1 star</option>

...

</select>
<textarea name="body" ng-model="reviewCtrl.review.body"></textarea>
<label>by:</label>
<input name="author" ng-model="reviewCtrl.review.author" type="email" />
<input type="submit" value="Submit" />

</form>
>
Now with validation.
index.html
required
novalidate
required
required
Turn Off Default HTML Validation
Mark Required Fields
Print Forms Validity<div> reviewForm is {{reviewForm.$valid}} </div>
<form name="reviewForm" ng-controller="ReviewController as reviewCtrl"
ng-submit="reviewCtrl.addReview(product)" >
<select ng-model="reviewCtrl.review.stars"
<option value="1">1 star</option>

...

</select>
>
<textarea name="body" ng-model="reviewCtrl.review.body" ></textarea>
<label>by:</label>
<input name="author" ng-model="reviewCtrl.review.author" type="email" />
<input type="submit" value="Submit" />

</form>
With validations
We don’t want the
form to submit
when it’s invalid.
<form name="reviewForm" ng-controller="ReviewController as reviewCtrl"
ng-submit="reviewCtrl.addReview(product)" novalidate>
Preventing the Submit
index.html
We only want this method to be called
if reviewForm.$valid is true.
<form name="reviewForm" ng-controller="ReviewController as reviewCtrl"
ng-submit="reviewForm.$valid && reviewCtrl.addReview(product)" novalidate>
Preventing the Submit
index.html
If valid is false, then addReview is
never called.
Doesn’t Submit an Invalid Form
How might we give a hint to the user
why their form is invalid?
The Input Classes index.html
Source before typing email
<input name="author" ng-model="reviewCtrl.review.author" type="email" required />
<input name="author" . . . class="ng-pristine ng-invalid">
Source after typing, with invalid email
<input name="author". . . class="ng-dirty ng-invalid">
Source after typing, with valid email
<input name="author" . . . class="ng-dirty ng-valid">
So, let’s highlight the form field using classes after we start typing,
showing if a field is valid or invalid. ng-valid ng-invalid
ng-dirty
.ng-invalid.ng-dirty {

border-color: #FA787E;

}
!
.ng-valid.ng-dirty {

border-color: #78FA89;

}
The classes
index.html
style.css
Red border for invalid
Green border for valid
<input name="author" ng-model="reviewCtrl.review.author" type="email" required />
Now with red and green borders!
Web forms usually have rules around valid input:
• Angular JS has built-in validations for common input types:
HTML5-based type validations
<input type="email" name="email">
min=1 max=10
Can also define min
& max with numbers
<input type="url" name="homepage">
<input type="number" name="quantity">
Shaping Up with Angular JS
Level 4: Creating a Directive with an
Associated Controller
Decluttering our Code
index.html
We’re going to have multiple pages that want to reuse this HTML
snippet.
How do we eliminate this duplication?
<ul class="list-group">

<li class="list-group-item" ng-repeat="product in store.products">
<h3>
{{product.name}} 

<em class="pull-right">${{product.price}}</em>
</h3>
<section ng-controller="PanelController as panel">
. . .
Using ng-include for Templates
index.html
product-title.html
<h3 ng-include="'product-title.html'" class="ng-scope">

<span class="ng-scope ng-binding">Awesome Multi-touch Keyboard</span>

<em class="pull-right ng-scope ng-binding">$250.00</em>

</h3>
generated html
ng-include is expecting a variable with the name of the file to include.

To pass the name directly as a string, use single quotes ('...')
<ul class="list-group">

<li class="list-group-item" ng-repeat="product in store.products">
<h3 name of file to includeng-include="'product-title.html'"
</h3>
<section ng-controller="PanelController as panel">
>
{{product.name}} 

<em class="pull-right">${{product.price}}</em>
Web Server
HTML JavaScript
Response with Webpage & Assets
Web Browser
URL Request to server
HTML Returned
Fetches ng-included file HTML
Browser loads up
Angular app.
<h3 ng-include="'product-title.html'"></h3>
Creating our First Custom Directive
index.html
Custom Directive
Using ng-include...
Our old code and our custom Directive will do the same thing...
with some additional code.
<product-title></product-title> index.html
Why write a Directive?
Why Directives?
Directives allow you to write HTML that expresses the behavior
of your application.
Can you tell what
this does?<aside class="col-sm-3">

<book-cover></book-cover>

<h4><book-rating></book-rating></h4>

</aside>



<div class="col-sm-9">

<h3><book-title></book-title></h3>



<book-authors></book-authors>



<book-review-text></book-review-text>



<book-genres></book-genres>

</div>
Template-expanding Directives are the simplest:
• define a custom tag or attribute that is expanded or replaced
• can include Controller logic, if needed
Writing Custom Directives
Directives can also be used for:
•Expressing complex UI
•Calling events and registering event handlers
•Reusing common components
app.directive('productTitle', function(){

return {
!
};

});
How to Build Custom Directives
app.js
<product-title></product-title> index.html
A configuration object defining how your directive will work
app.directive('productTitle', function(){

return {
!
!
};

});
How to Build Custom Directives
app.js
<product-title></product-title> index.html
<h3>

{{product.name}}

<em class="pull-right">$250.00</em>

</h3>
index.html
Type of Directive

(E for Element)
Url of a template
generates
into
restrict: 'E',
templateUrl: 'product-title.html'
camelCase in JavaScriptdash in HTML translates to ...
index.html
Attribute vs Element Directives
Element Directive
Attribute Directive
…some browsers don’t like self-closing tags.
Use Element Directives for UI widgets and Attribute Directives for
mixin behaviors... like a tooltip.
index.html
Notice we’re not using a self-closing tag…
<product-title></product-title>
<h3 product-title></h3>
<product-title/>
index.html
Defining an Attribute Directive
app.js
<h3>

{{product.name}}

<em class="pull-right">$250.00</em>

</h3>
index.html
generates
into
<h3 product-title></h3>
app.directive('productTitle', function(){

return {
!


};

});
Though normally attributes would be for mixin behaviors ...
restrict: 'A',
templateUrl: 'product-title.html'
Type of Directive

(A for Attribute)
When you think of a dynamic web application, do you think
you’ll be able to understand the functionality just by looking at
the HTML?
Directives allow you to write better HTML
When you're writing an Angular JS application, you should be
able to understand the behavior and intent from just the HTML.
No, right?
And you’re likely using custom directives to write expressive
HTML.
Shaping Up with Angular JS
Creating Our Own Directives
<h3> 

{{product.name}} 

<em class="pull-right">${{product.price}}</em>
</h3>
Reviewing our Directive
index.html
Template-Expanding Directives
An Attribute Directive
An Element Directive
<h3 product-title></h3>
<h3> <product-title></product-title> </h3>
What if we need a Controller?
index.html
}Directive?
ng-controller="PanelController as panels"
<ul class="nav nav-pills"> . . . </ul>

<div class="panel" ng-show="panels.isSelected(1)"> . . . </div>

<div class="panel" ng-show="panels.isSelected(2)"> . . . </div>

<div class="panel" ng-show="panels.isSelected(3)"> . . . </div>
</section>
><section
First, extract the template...
product-panels.html
index.html
><section
<ul class="nav nav-pills"> . . . </ul>

<div class="panel" ng-show="panels.isSelected(1)"> . . . </div>

<div class="panel" ng-show="panels.isSelected(2)"> . . . </div>

<div class="panel" ng-show="panels.isSelected(3)"> . . . </div>
</section>
<h3> <product-title> </h3>
ng-controller="PanelController as panels"
. . .
</product-panels>
<product-panels >
Now write the Directive ...
app.js
index.html
ng-controller="PanelController as panels"
. . .
</product-panels>
<product-panels >
app.directive('productPanels', function(){

return {
restrict: 'E',
templateUrl: 'product-panels.html'
};

});
What about the Controller?
app.js
index.html
ng-controller="PanelController as panels"
. . .
</product-panels>
<product-panels >
app.directive('productPanels', function(){

return {
restrict: 'E',
templateUrl: 'product-panels.html'
};

});
app.controller('PanelController', function(){
. . .
});
First we need to move the functionality inside the directive
Moving the Controller Inside
app.js
index.html
ng-controller="PanelController as panels"
. . .
</product-panels>
<product-panels >
app.directive('productPanels', function(){

return {
restrict: 'E',
templateUrl: 'product-panels.html'
};

});
,
Next, move the alias inside
function(){
. . .
controller:
}
Need to Specify the Alias
app.js
index.html
Now it works, using panels as our Controller Alias.
. . .
</product-panels>
<product-panels>
controllerAs: 'panels'
};
});
app.directive('productPanels', function(){

return {
restrict: 'E',
templateUrl: 'product-panels.html'
};

});
,
,
function(){
. . .
controller:
}
Challenges
Shaping Up with Angular JS
Level 5: Dependencies and Services
(function(){

var app = angular.module('store', [
Starting to get a bit cluttered?
app.js
Can we refactor
these out?
. . .

})();
app.controller('StoreController', function(){ . . . });
]);
app.directive('productTitle', function(){ . . . });
!
app.directive('productGallery', function(){ . . . });
!
app.directive('productPanels', function(){ . . . });
(function(){

var app = angular.module('store', [
Extract into a new file ... products.js
app.js
. . .

})();
app.controller('StoreController', function(){ . . . });
]);
products.js
app.directive('productTitle', function(){ . . . });
!
app.directive('productGallery', function(){ . . . });
!
app.directive('productPanels', function(){ . . . });
(function(){

var app = angular.module('store', [
Make a new Module
app.js
. . .

})();
app.controller('StoreController', function(){ . . . });
]);
products.js
(function(){

var app = angular.module('store
})();
-products', [ ]);
Define a new module just
for Product stuff...
Module Name
Different closure
means different
app variable.
app.directive('productTitle', function(){ . . . });
!
app.directive('productGallery', function(){ . . . });
!
app.directive('productPanels', function(){ . . . });
(function(){

var app = angular.module('store', [
Add it to the dependencies ...
app.js
. . .

})();
app.controller('StoreController', function(){ . . . });
]);
app.directive('productTitle', function(){ . . . });
app.directive('productGallery', function(){ . . . });
app.directive('productPanels', function(){ . . . });
products.js
(function(){

var app = angular.module('store
})();
-products', [ ]);
'store-products'
Module Name
store depends on
store-products
<!DOCTYPE html>

<html ng-app="store">

<head> . . . </head>

<body ng-controller="StoreController as store">

. . .

<script src="angular.js"></script>

<script src="app.js"></script>
We’ll also need to include the file
index.html
</body>

</html>
<script src="products.js"></script>

Best to split Modules around functionality:
• app.js – top-level module attached via ng-app
• products.js – all the functionality for products and only products
How should I organize my application Modules?
Challenges
Does this feel strange?
app.js
What is all this data
doing here?
Where can we put it?
Shouldn't we fetch this from an API?
(function(){

var app = angular.module('store', [ 'store-products' ]);



app.controller('StoreController', function(){

this.products = [
{ name: '. . .', price: 1.99, . . . },

{ name: '. . .', price: 1.99, . . . },

{ name: '. . .', price: 1.99, . . . },
. . . 

});

})();
. . .

];
How do we get that data?
app.js
How do we fetch our
products from an API?
http://api.example.com/products.json
(function(){

var app = angular.module('store', [ 'store-products' ]);



app.controller('StoreController', function(){

this.products = ???;
. . . 

});

})();
{ name: '. . .', price: 1.99, . . . },

{ name: '. . .', price: 1.99, . . . },

{ name: '. . .', price: 1.99, . . . },
[
. . .

]
Services give your Controller additional functionality, like ...
• Fetching JSON data from a web service with $http
• Logging messages to the JavaScript console with $log
• Filtering an array with $filter
We need a Service!
All built-in Services
start with a $
sign ...
The $http Service is how we make an async request to a server ...
• By using $http as a function with an options object:
Introducing the $http Service!
So how do we use it?
$http({ method: 'GET', url: '/products.json' });
• Or using one of the shortcut methods:
$http.get('/products.json', { apiKey: 'myApiKey' });
• Both return a Promise object with .success() and .error()
• If we tell $http to fetch JSON, the result will be automatically
decoded into JavaScript objects and arrays
Use this funky array syntax:
app.controller('SomeController', [ '$http', function($http){



} ]);
How does a Controller use a Service like $http?
Service name
Service name as an argument
Dependency Injection!
app.controller('SomeController', [ '$http', '$log', function($http, $log){



} ]);
If you needed more than one
When Angular is Loaded Services are Registered
SomeController $http
Injector
$log
app.controller('SomeController', [ '$http', '$log', function($http, $log){



} ]);
app.controller('SomeController', [ '$http', '$log', function($http, $log){



} ]);
A Controller is Initialized
SomeController $http
Injector
$log
and $log, too ...
I need $http ...
Psst...
When I run...
app.controller('SomeController', [ '$http', '$log', function($http, $log){



} ]);
Then When the Controller runs ...
SomeController $http
Injector
$log
Here ya go!
Dependency Injection!
(function(){

var app = angular.module('store', [ 'store-products' ]);



app.controller('StoreController',
So where were we?
app.js
){function(
this.products = ???;
);}
})();
(function(){

var app = angular.module('store', [ 'store-products' ]);



app.controller('StoreController',
Time for your injection!
app.js
){function(
this.products = ???;
);}
})();
[ '$http',
StoreController needs
the $http Service...
...so $http
gets injected
as an argument!
Now what?
$http
]
(function(){

var app = angular.module('store', [ 'store-products' ]);



app.controller('StoreController',
Let’s use our Service!
app.js
){function(
this.products = ???;
);}
})();
[ '$http', $http
$http.get('/products.json')
Fetch the contents of
products.json...
]
(function(){

var app = angular.module('store', [ 'store-products' ]);



app.controller('StoreController',
Our Service will Return Data
app.js
){function(
this.products = ???;
);}
})();
[ '$http', $http
$http.get('/products.json').success(function(data){
???
});
= data;
$http returns a Promise, so
success() gets the data...
What do we assign
data to, though...?
]
(function(){

var app = angular.module('store', [ 'store-products' ]);



app.controller('StoreController',
Storing the Data for use in our Page
app.js
){function(
);}
})();
[ '$http', $http
$http.get('/products.json').success(function(data){
});
= data;
var store = this;
store.products
We need to store what this is ...
... and now we have somewhere 

to put our data!
But the page might look funny until the data loads.
]
(function(){

var app = angular.module('store', [ 'store-products' ]);



app.controller('StoreController',
Initialize Products to be a Blank Array
app.js
){function(
);}
})();
[ '$http', $http
$http.get('/products.json').success(function(data){
});
= data;
var store = this;
store.products
store.products = [ ];
We need to initialize products to an empty
array, since the page will render before our
data returns from our get request.
]
$http.post('/path/to/resource.json', { param: 'value' });
Additional $http functionality
$http({ method: 'PATCH', url: '/path/to/resource.json' });
$http({ method: 'TRACE', url: '/path/to/resource.json' });
In addition to get() requests, $http can post(), put(), delete()...
$http.delete('/path/to/resource.json');
$http({ method: 'OPTIONS', url: '/path/to/resource.json' });
...or any other HTTP method by using a config object:
Challenges
Course CodeSchool - Shaping up with Angular.js

Contenu connexe

Tendances

Introduction to AngularJS Framework
Introduction to AngularJS FrameworkIntroduction to AngularJS Framework
Introduction to AngularJS FrameworkRaveendra R
 
AngularJS Introduction
AngularJS IntroductionAngularJS Introduction
AngularJS IntroductionBrajesh Yadav
 
Controller in AngularJS
Controller in AngularJSController in AngularJS
Controller in AngularJSBrajesh Yadav
 
Orchard Harvest 2014 - The Future of Widgets?
Orchard Harvest 2014 - The Future of Widgets?Orchard Harvest 2014 - The Future of Widgets?
Orchard Harvest 2014 - The Future of Widgets?Steve Taylor
 
AtlasCamp 2015: Using add-ons to build add-ons
AtlasCamp 2015: Using add-ons to build add-onsAtlasCamp 2015: Using add-ons to build add-ons
AtlasCamp 2015: Using add-ons to build add-onsAtlassian
 
Understanding angular js $rootscope and $scope
Understanding angular js $rootscope and $scopeUnderstanding angular js $rootscope and $scope
Understanding angular js $rootscope and $scopeBrajesh Yadav
 
Why angular js Framework
Why angular js Framework Why angular js Framework
Why angular js Framework Sakthi Bro
 
AtlasCamp 2015: Connect everywhere - Cloud and Server
AtlasCamp 2015: Connect everywhere - Cloud and ServerAtlasCamp 2015: Connect everywhere - Cloud and Server
AtlasCamp 2015: Connect everywhere - Cloud and ServerAtlassian
 
AtlasCamp 2015: Web technologies you should be using now
AtlasCamp 2015: Web technologies you should be using nowAtlasCamp 2015: Web technologies you should be using now
AtlasCamp 2015: Web technologies you should be using nowAtlassian
 
AngularJS Project Setup step-by- step guide - RapidValue Solutions
AngularJS Project Setup step-by- step guide - RapidValue SolutionsAngularJS Project Setup step-by- step guide - RapidValue Solutions
AngularJS Project Setup step-by- step guide - RapidValue SolutionsRapidValue
 
Introduction to Android Programming
Introduction to Android ProgrammingIntroduction to Android Programming
Introduction to Android ProgrammingRaveendra R
 
Angular JS blog tutorial
Angular JS blog tutorialAngular JS blog tutorial
Angular JS blog tutorialClaude Tech
 
Building Progressive Web Apps for Android and iOS
Building Progressive Web Apps for Android and iOSBuilding Progressive Web Apps for Android and iOS
Building Progressive Web Apps for Android and iOSFITC
 

Tendances (20)

Introduction to AngularJS Framework
Introduction to AngularJS FrameworkIntroduction to AngularJS Framework
Introduction to AngularJS Framework
 
AngularJS Introduction
AngularJS IntroductionAngularJS Introduction
AngularJS Introduction
 
Custom directive and scopes
Custom directive and scopesCustom directive and scopes
Custom directive and scopes
 
Training On Angular Js
Training On Angular JsTraining On Angular Js
Training On Angular Js
 
AspNetWhitePaper
AspNetWhitePaperAspNetWhitePaper
AspNetWhitePaper
 
Angular js
Angular jsAngular js
Angular js
 
Controller in AngularJS
Controller in AngularJSController in AngularJS
Controller in AngularJS
 
Orchard Harvest 2014 - The Future of Widgets?
Orchard Harvest 2014 - The Future of Widgets?Orchard Harvest 2014 - The Future of Widgets?
Orchard Harvest 2014 - The Future of Widgets?
 
AngularJS Best Practices
AngularJS Best PracticesAngularJS Best Practices
AngularJS Best Practices
 
AtlasCamp 2015: Using add-ons to build add-ons
AtlasCamp 2015: Using add-ons to build add-onsAtlasCamp 2015: Using add-ons to build add-ons
AtlasCamp 2015: Using add-ons to build add-ons
 
Understanding angular js $rootscope and $scope
Understanding angular js $rootscope and $scopeUnderstanding angular js $rootscope and $scope
Understanding angular js $rootscope and $scope
 
Why angular js Framework
Why angular js Framework Why angular js Framework
Why angular js Framework
 
AtlasCamp 2015: Connect everywhere - Cloud and Server
AtlasCamp 2015: Connect everywhere - Cloud and ServerAtlasCamp 2015: Connect everywhere - Cloud and Server
AtlasCamp 2015: Connect everywhere - Cloud and Server
 
AtlasCamp 2015: Web technologies you should be using now
AtlasCamp 2015: Web technologies you should be using nowAtlasCamp 2015: Web technologies you should be using now
AtlasCamp 2015: Web technologies you should be using now
 
EVOLVE'14 | Enhance | Gabriel Walt | Sightly Component Development
EVOLVE'14 | Enhance | Gabriel Walt | Sightly Component DevelopmentEVOLVE'14 | Enhance | Gabriel Walt | Sightly Component Development
EVOLVE'14 | Enhance | Gabriel Walt | Sightly Component Development
 
AngularJS
AngularJSAngularJS
AngularJS
 
AngularJS Project Setup step-by- step guide - RapidValue Solutions
AngularJS Project Setup step-by- step guide - RapidValue SolutionsAngularJS Project Setup step-by- step guide - RapidValue Solutions
AngularJS Project Setup step-by- step guide - RapidValue Solutions
 
Introduction to Android Programming
Introduction to Android ProgrammingIntroduction to Android Programming
Introduction to Android Programming
 
Angular JS blog tutorial
Angular JS blog tutorialAngular JS blog tutorial
Angular JS blog tutorial
 
Building Progressive Web Apps for Android and iOS
Building Progressive Web Apps for Android and iOSBuilding Progressive Web Apps for Android and iOS
Building Progressive Web Apps for Android and iOS
 

Similaire à Course CodeSchool - Shaping up with Angular.js

AngularJS Mobile Warsaw 20-10-2014
AngularJS Mobile Warsaw 20-10-2014AngularJS Mobile Warsaw 20-10-2014
AngularJS Mobile Warsaw 20-10-2014Dariusz Kalbarczyk
 
intro to Angular js
intro to Angular jsintro to Angular js
intro to Angular jsBrian Atkins
 
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosAngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosLearnimtactics
 
AngularJS for Legacy Apps
AngularJS for Legacy AppsAngularJS for Legacy Apps
AngularJS for Legacy AppsPeter Drinnan
 
Introduction to angular js july 6th 2014
Introduction to angular js   july 6th 2014Introduction to angular js   july 6th 2014
Introduction to angular js july 6th 2014Simona Clapan
 
Introduction of angular js
Introduction of angular jsIntroduction of angular js
Introduction of angular jsTamer Solieman
 
An introduction to AngularJS
An introduction to AngularJSAn introduction to AngularJS
An introduction to AngularJSYogesh singh
 
ASP.NET MVC, AngularJS CRUD for Azerbaijan Technical University
ASP.NET MVC, AngularJS CRUD for Azerbaijan Technical UniversityASP.NET MVC, AngularJS CRUD for Azerbaijan Technical University
ASP.NET MVC, AngularJS CRUD for Azerbaijan Technical UniversitySyed Shanu
 
AgularJS basics- angular directives and controllers
AgularJS basics- angular directives and controllersAgularJS basics- angular directives and controllers
AgularJS basics- angular directives and controllersjobinThomas54
 
AngularJS interview questions
AngularJS interview questionsAngularJS interview questions
AngularJS interview questionsUri Lukach
 
Building a dashboard using AngularJS
Building a dashboard using AngularJSBuilding a dashboard using AngularJS
Building a dashboard using AngularJSRajthilakMCA
 
SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015Pushkar Chivate
 

Similaire à Course CodeSchool - Shaping up with Angular.js (20)

AngularJS Mobile Warsaw 20-10-2014
AngularJS Mobile Warsaw 20-10-2014AngularJS Mobile Warsaw 20-10-2014
AngularJS Mobile Warsaw 20-10-2014
 
intro to Angular js
intro to Angular jsintro to Angular js
intro to Angular js
 
Angular js
Angular jsAngular js
Angular js
 
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle StudiosAngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
 
Angular - Beginner
Angular - BeginnerAngular - Beginner
Angular - Beginner
 
AngularJS for Legacy Apps
AngularJS for Legacy AppsAngularJS for Legacy Apps
AngularJS for Legacy Apps
 
Let's react - Meetup
Let's react - MeetupLet's react - Meetup
Let's react - Meetup
 
Starting with angular js
Starting with angular js Starting with angular js
Starting with angular js
 
Ng-init
Ng-init Ng-init
Ng-init
 
Ng-init
Ng-init Ng-init
Ng-init
 
Introduction to angular js july 6th 2014
Introduction to angular js   july 6th 2014Introduction to angular js   july 6th 2014
Introduction to angular js july 6th 2014
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Introduction of angular js
Introduction of angular jsIntroduction of angular js
Introduction of angular js
 
An introduction to AngularJS
An introduction to AngularJSAn introduction to AngularJS
An introduction to AngularJS
 
ASP.NET MVC, AngularJS CRUD for Azerbaijan Technical University
ASP.NET MVC, AngularJS CRUD for Azerbaijan Technical UniversityASP.NET MVC, AngularJS CRUD for Azerbaijan Technical University
ASP.NET MVC, AngularJS CRUD for Azerbaijan Technical University
 
AgularJS basics- angular directives and controllers
AgularJS basics- angular directives and controllersAgularJS basics- angular directives and controllers
AgularJS basics- angular directives and controllers
 
Dive into AngularJS and directives
Dive into AngularJS and directivesDive into AngularJS and directives
Dive into AngularJS and directives
 
AngularJS interview questions
AngularJS interview questionsAngularJS interview questions
AngularJS interview questions
 
Building a dashboard using AngularJS
Building a dashboard using AngularJSBuilding a dashboard using AngularJS
Building a dashboard using AngularJS
 
SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015
 

Dernier

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Orbitshub
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century educationjfdjdjcjdnsjd
 

Dernier (20)

Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 

Course CodeSchool - Shaping up with Angular.js

  • 1.
  • 2. Shaping Up with Angular Level 1: Getting Started
  • 3. What you need to know Must know Not so important Nice to know Automated Testing BDD - Behavior Driven Development TDD - Test Driven Development etc HTML & CSS JavaScript jQuery Ruby on Rails Python, PHP, etc Databases
  • 4. Why Angular? If you’re using JavaScript to create a dynamic website, Angular is a good choice. • Angular helps you organize your JavaScript • Angular helps create responsive (as in fast) websites. • Angular plays well with jQuery • Angular is easy to test
  • 5. Traditional Page-Refresh Screencast: Request-Response Application NOTE: Time between user 
 interaction and response.
  • 6. Web Server HTML JavaScript Response with Webpage & Assets Web Browser URL Request to server Response with Webpage & Assets User clicks on link, new Request HTML JavaScript Browser loads up entire webpage. Browser loads up entire webpage.
  • 7. Screencast: Request-Response Application NOTE: Note how responsive the page is A “responsive” website using Angular
  • 8. Web Server Response with Webpage & Assets Web Browser URL Request to server Response with JSON Data User clicks on link, new Request HTML JavaScript DATA Browser loads up entire webpage. Data is loaded into existing page.
  • 9. Modern API-Driven Application HTML Browser App Data Source Mobile App Developers Server API
  • 10. A client-side JavaScript Framework for adding interactivity to HTML. app.jsindex.html How do we tell our HTML when to trigger our JavaScript? <!DOCTYPE html>
 <html>
 <body
 . . . </body>
 </html> function Store
 alert('Welcome, Gregg!');
 }
 (){ > What is Angular JS?
  • 11. <!DOCTYPE html>
 <html>
 <body
 . . . </body>
 </html> app.js function Store
 alert('Welcome, Gregg!');
 }
 A Directive is a marker on a HTML tag that tells Angular to run or reference some JavaScript code. Directives Name of function to callindex.html Controller(){ ng-controller="StoreController">
  • 12. The Flatlanders Store! Screencast: Flatlanders Store Fully Functional
  • 13. Download AngularJS http://angularjs.org/ We’ll need angular.min.js Downloading the libraries Download Twitter Bootstrap http://getbootstrap.com/ We’ll need bootstrap.min.css
  • 14. <!DOCTYPE html>
 <html>
 <head>
 <link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
 </head>
 <body>
 <script type="text/javascript" src="angular.min.js"></script>
 </body>
 </html> Getting Started index.html Twitter Bootstrap AngularJS
  • 15. Modules • Where we write pieces of our Angular application. • Makes our code more maintainable, testable, and readable. • Where we define dependencies for our app. Modules can use other Modules...
  • 16. Creating Our First Module Dependencies Other libraries we might need. 
 We have none... for now… Application Name AngularJS var app = angular.module('store', [ ]);
  • 17. Including Our Module var app = angular.module('store', [ ]); app.js index.html <!DOCTYPE html>
 <html>
 <head>
 <link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
 </head>
 <body>
 <script type="text/javascript" src="angular.min.js"></script> <script type="text/javascript" src="app.js"></script> </body>
 </html>
  • 18. Including Our Module var app = angular.module('store', [ ]); app.js <!DOCTYPE html>
 <html ng-app="store">
 <head>
 <link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
 </head>
 <body>
 <script type="text/javascript" src="angular.min.js"></script>
 <script type="text/javascript" src="app.js"></script>
 </body>
 </html> Run this module when the document loads. index.html
  • 19. Allow you to insert dynamic values into your HTML. Expressions Numerical Operations evaluates to String Operations evaluates to + More Operations: http://docs.angularjs.org/guide/expression <p>
 I am {{4 + 6}}
 </p> <p>
 {{"hello" + " you"}}
 </p> <p>
 I am 10
 </p> <p>
 hello you
 </p>

  • 20. Including Our Module var app = angular.module('store', [ ]); app.js <!DOCTYPE html>
 <html ng-app="store">
 <head>
 <link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
 </head>
 <body>
 <script type="text/javascript" src="angular.min.js"></script>
 <script type="text/javascript" src="app.js"></script>
 <p>{{"hello" + " you"}}</p> </body>
 </html> index.html
  • 22. Working With Data ...just a simple object we want to print to the page. var gem = {
 name: 'Dodecahedron',
 price: 2.95,
 description: '. . .',
 }.
  • 23. Controllers app.js Notice that controller is attached to (inside) our app. Controllers are where we define our app’s behavior by defining functions and values. Wrapping your Javascript in a closure is a good habit! var gem = {
 name: 'Dodecahedron',
 price: 2.95,
 description: '. . .',
 }. })(); (function(){
 var app = angular.module('store', [ ]); app.controller('StoreController', function(){
 
 });
  • 24. Storing Data Inside the Controller app.js Now how do we print out this data inside our webpage? this.product = gem; var gem = {
 name: 'Dodecahedron',
 price: 2.95,
 description: '. . .',
 }. })(); (function(){
 var app = angular.module('store', [ ]); app.controller('StoreController', function(){
 
 });
  • 25. <!DOCTYPE html>
 <html ng-app="store">
 <head>
 <link rel="stylesheet" type="text/css" href="bootstrap.min.css" />
 </head>
 ! ! ! ! ! ! ! ! </html>
 <body>
 <div>
 <h1> Product Name </h1>
 <h2> $Product Price </h2>
 <p> Product Description </p>
 </div>
 <script type="text/javascript" src="angular.min.js"></script>
 <script type="text/javascript" src="app.js"></script>
 </body> Our Current HTML Let’s load our data into this part of the page. } index.html
  • 26. <body>
 <div>
 <h1> Product Name </h1>
 <h2> $Product Price </h2>
 <p> Product Description </p>
 </div>
 <script type="text/javascript" src="angular.min.js"></script>
 <script type="text/javascript" src="app.js"></script>
 </body> (function(){
 var app = angular.module('store', [ ]);
 
 app.controller('StoreController', function(){
 this.product = gem; }); . . . })(); app.js index.html Attaching the Controller
  • 27. <body>
 <div ng-controller="StoreController as store">
 <h1> Product Name </h1>
 <h2> $Product Price </h2>
 <p> Product Description </p>
 </div>
 <script type="text/javascript" src="angular.min.js"></script>
 <script type="text/javascript" src="app.js"></script>
 </body> Attaching the Controller (function(){
 var app = angular.module('store', [ ]);
 
 app.controller('StoreController', function(){
 this.product = gem; }); . . . })(); app.js index.html Controller name AliasDirective
  • 28. <body>
 <div ng-controller="StoreController as store">
 ! ! </div>
 <script type="text/javascript" src="angular.min.js"></script>
 <script type="text/javascript" src="app.js"></script>
 </body> index.html Displaying Our First Product (function(){
 var app = angular.module('store', [ ]);
 
 app.controller('StoreController', function(){
 this.product = gem; }); . . . })(); app.js <h1> {{store.product.name}} </h1>
 <h2> ${{store.product.price}} </h2>
 <p> {{store.product.description}} </p>
  • 29. Understanding Scope Would never print a value! The scope of the Controller is only inside here... }{{store.product.name}} <h1> {{store.product.name}} </h1>
 <h2> ${{store.product.price}} </h2>
 <p> {{store.product.description}} </p> <body>
 <div ng-controller="StoreController as store">
 ! ! </div>
 <script type="text/javascript" src="angular.min.js"></script>
 <script type="text/javascript" src="app.js"></script>
 </body>
  • 31. </div>
 <script type="text/javascript" src="angular.min.js"></script>
 <script type="text/javascript" src="app.js"></script>
 </body> <body ng-controller="StoreController as store">
 <div>
 <h1> {{store.product.name}} </h1>
 <h2> ${{store.product.price}} </h2>
 <p> {{store.product.description}} </p> Adding A Button index.html var gem = {
 name: 'Dodecahedron',
 price: 2.95,
 description: '. . .', }.
  • 32. var gem = {
 name: 'Dodecahedron',
 price: 2.95,
 description: '. . .', }. canPurchase: false </div>
 <script type="text/javascript" src="angular.min.js"></script>
 <script type="text/javascript" src="app.js"></script>
 </body> Adding A Button index.html <button How can we only show this button... ...when this is true? Directives tothe rescue! <body ng-controller="StoreController as store">
 <div>
 <h1> {{store.product.name}} </h1>
 <h2> ${{store.product.price}} </h2>
 <p> {{store.product.description}} </p> > Add to Cart </button>
  • 33. var gem = {
 name: 'Dodecahedron',
 price: 2.95,
 description: '. . .', }. canPurchase: false </div>
 <script type="text/javascript" src="angular.min.js"></script>
 <script type="text/javascript" src="app.js"></script>
 </body> NgShow Directive index.html <button <body ng-controller="StoreController as store">
 <div>
 <h1> {{store.product.name}} </h1>
 <h2> ${{store.product.price}} </h2>
 <p> {{store.product.description}} </p> ng-show="store.product.canPurchase"> Add to Cart </button> Will only show the element if the value of the Expression is true.
  • 34.
  • 35. </div>
 <script type="text/javascript" src="angular.min.js"></script>
 <script type="text/javascript" src="app.js"></script>
 </body> index.html <button <body ng-controller="StoreController as store">
 <div
 <h1> {{store.product.name}} </h1>
 <h2> ${{store.product.price}} </h2>
 <p> {{store.product.description}} </p> ng-show="store.product.canPurchase"> Add to Cart </button> NgHide Directive If the product is sold out we want to hide it. var gem = {
 name: 'Dodecahedron',
 price: 2.95,
 description: '. . .', }. canPurchase: true, soldOut: true >
  • 36. </div>
 <script type="text/javascript" src="angular.min.js"></script>
 <script type="text/javascript" src="app.js"></script>
 </body> index.html <button <body ng-controller="StoreController as store">
 <div
 <h1> {{store.product.name}} </h1>
 <h2> ${{store.product.price}} </h2>
 <p> {{store.product.description}} </p> ng-show="store.product.canPurchase"> Add to Cart </button> NgHide Directive If the product is sold out we want to hide it. This is awkward and a good example to use ng-hide! var gem = {
 name: 'Dodecahedron',
 price: 2.95,
 description: '. . .', }. canPurchase: true, soldOut: true, ng-show="!store.product.soldOut">
  • 37. </div>
 <script type="text/javascript" src="angular.min.js"></script>
 <script type="text/javascript" src="app.js"></script>
 </body> index.html <button <body ng-controller="StoreController as store">
 <div
 <h1> {{store.product.name}} </h1>
 <h2> ${{store.product.price}} </h2>
 <p> {{store.product.description}} </p> ng-show="store.product.canPurchase"> Add to Cart </button> NgHide Directive If the product is sold out we want to hide it. Much better! var gem = {
 name: 'Dodecahedron',
 price: 2.95,
 description: '. . .', }. canPurchase: true, soldOut: true, ng-hide="store.product.soldOut">
  • 38. Multiple Products app.js var gem = 
 name: "Dodecahedron",
 price: 2.95,
 description: ". . .",
 canPurchase: true,
 },
 { app.controller('StoreController', function(){
 this.product = gem
 });
 ;
  • 39. Multiple Products app.js var gems = [
 
 name: "Dodecahedron",
 price: 2.95,
 description: ". . .",
 canPurchase: true,
 },
 {
 name: "Pentagonal Gem",
 price: 5.95,
 description: ". . .",
 canPurchase: false,
 }…
 ]; { Now we have an array... How might we display all these products in our template? Maybe a Directive? app.controller('StoreController', function(){
 this.products = gems
 });
 ; So we have multiple products...
  • 40. Working with An Array index.html <body ng-controller="StoreController as store">
 <div>
 <h1> {{store.products[0].name}} </h1>
 <h2> ${{store.products[0].price}} </h2>
 <p> {{store.products[0].description}} </p>
 <button ng-show="store.products[0].canPurchase">
 Add to Cart</button>
 </div>
 . . .
 </body>
  • 41. index.html Working with An Array . . .
 </body> Displaying the first product is easy enough... <body ng-controller="StoreController as store">
 <div>
 <h1> {{store.products[0].name}} </h1>
 <h2> ${{store.products[0].price}} </h2>
 <p> {{store.products[0].description}} </p>
 <button ng-show="
 Add to Cart</button>
 </div> store.products[0].canPurchase">
  • 42. Working with An Array index.html <body ng-controller="StoreController as store">
 <div
 <h1> {{store.products[0].name}} </h1>
 <h2> ${{store.products[0].price}} </h2>
 <p> {{store.products[0].description}} </p>
 <button ng-show="
 Add to Cart</button>
 </div> . . .
 </body> <div>
 <h1> {{store.products[1].name}} </h1>
 <h2> ${{store.products[1].price}} </h2>
 <p> {{store.products[1].description}} </p>
 <button ng-show="store.products[1].canPurchase">
 Add to Cart</button>
 </div> Why repeat yourself? Why repeat yourself? Why... You get it. > store.products[0].canPurchase"> That works...
  • 43. Working with An Array index.html <body ng-controller="StoreController as store">
 <div
 <h1> {{product.name}} </h1>
 <h2> ${{product.price}} </h2>
 <p> {{product.description}} </p>
 <button ng-show="
 Add to Cart</button>
 </div> . . .
 </body> ng-repeat="product in store.products" product > Repeat this section for each product. }.canPurchase">
  • 44. What We Have Learned So Far Directives – HTML annotations that trigger Javascript behaviors Modules – Where our application components live Controllers – Where we add application behavior Expressions – How values get displayed within the page
  • 46.
  • 47.
  • 48. Shaping Up with Angular.JS Level 2: Filters, Directives, and Cleaner Code
  • 49. ng-app – attach the Application Module to the page Directives We Know & Love ng-controller – attach a Controller function to the page ng-show / ng-hide – display a section based on an Expression ng-repeat – repeat a section for each item in an Array <html ng-app="store"> <body ng-controller="StoreController as store"> <h1 ng-show="name"> Hello, {{name}}! </h1> <li ng-repeat="product in store.products"> {{product.name}} </li>
  • 50. Our Current Code <body ng-controller="StoreController as store">
 <ul class="list-group">
 <li class="list-group-item" ng-repeat="product in store.products">
 <h3> 
 {{product.name}} index.html <em class="pull-right">${{product.price </em>}} </h3>
 </li>
 </ul>
 </body> There’s a better way to print out prices. $2
  • 51. Our First Filter Pipe - “send the output into” Format this into currency Notice it gives the dollar sign (localized) Specifies number of decimals index.html <em class="pull-right">{{product.price | currency </em>}} <body ng-controller="StoreController as store">
 <ul class="list-group">
 <li class="list-group-item" ng-repeat="product in store.products">
 <h3> 
 {{product.name}} </h3>
 </li>
 </ul>
 </body> $2.00
  • 52. {{ data | filter:options }} Formatting with Filters *Our Recipe {{'1388123412323' | date:'MM/dd/yyyy @ h:mma'}} date 12/27/2013 @ 12:50AM {{'octagon gem' | uppercase}} uppercase & lowercase OCTAGON GEM {{'My Description' | limitTo:8}} limitTo My Descr <li ng-repeat="product in store.products | orderBy:'-price'"> orderBy Will list products by descending price. Without the - products would list in ascending order. <li ng-repeat="product in store.products | limitTo:3"> * *
  • 53. var gems = [
 { name: 'Dodecahedron Gem', price: 2.95,
 description: '. . .',
 images: [
 { full: 'dodecahedron-01-full.jpg', thumb: 'dodecahedron-01-thumb.jpg'
 },
 { full: "dodecahedron-02-full.jpg", . . . Adding an Image Array to our Product Array Our New Array Image Object To display the first image in a product: {{product.images[0].full}} app.js
  • 54. <body ng-controller="StoreController as store">
 <ul class="list-group">
 <li class="list-group-item" ng-repeat="product in store.products">
 <h3> 
 {{product.name}} <em class="pull-right">{{product.price | currency}}</em> <img ng-src="{{product.images[0].full}}"/> </h3>
 </li>
 </ul>
 </body> index.html Using ng-src for Images NG-SOURCE to the rescue! …the browser tries to load the image before the Expression evaluates. Using Angular Expressions inside a src attribute causes an error! <img src="{{product.images[0].full}}"/>
  • 57. More With Directives How can I make my application more interactive?
  • 58. A Simple Set of Tabs index.html <section>
 <ul class="nav nav-pills”> <li> <a href <li> <a href <li> <a href >Description</a> </li> >Specifications</a> </li> >Reviews</a> </li> </ul> </section>
  • 59. Introducing a new Directive! index.html Assigning a value to tab. For now just print this value to the screen. <section>
 <ul class="nav nav-pills”> <li> <a href <li> <a href <li> <a href >Description</a> </li> >Specifications</a> </li> >Reviews</a> </li> {{tab}} ng-click="tab = 1" ng-click="tab = 2" ng-click="tab = 3" </ul> </section>
  • 60. Introducing a new Directive!
  • 61. When ng-click changes the value of tab … … the {{tab}} expression automatically gets updated! ! Expressions define a 2-way Data Binding ... this means Expressions are re-evaluated when a property changes. Whoa, it’s dynamic and stuff...
  • 62. <div class="panel" <div class="panel" Let’s add the tab content panels How do we make the tabs trigger the panel to show? <h4>Description</h4>
 <p>{{product.description}}</p>
 </div> <div class="panel" <h4>Specifications</h4>
 <blockquote>None yet</blockquote>
 </div> <h4>Reviews</h4>
 <blockquote>None yet</blockquote>
 </div> > > > tabs are up here... . . .
  • 63. Let’s add the tab content panels Now when a tab is selected it will show the appropriate panel! <div class="panel" > > > <h4>Description</h4>
 <p>{{product.description}}</p>
 </div> <h4>Specifications</h4>
 <blockquote>None yet</blockquote>
 </div> <h4>Reviews</h4>
 <blockquote>None yet</blockquote>
 </div> ng-show="tab === 1" ng-show="tab === 2" ng-show="tab === 3"<div class="panel" <div class="panel" show the panel if tab is the right number
  • 64. But how do we set an initial value for a tab?
  • 65. Setting the Initial Value index.html ng-init allows us to evaluate an expression in the current scope. <section ng-init="tab = 1"> <ul class="nav nav-pills">
 <li> <a href ng-click="tab = 1">Description</a> </li>
 <li> <a href ng-click="tab = 2">Specifications</a> </li>
 <li> <a href ng-click="tab = 3">Reviews</a> </li>
 </ul> . . .
  • 66. Now with the Initial Tab
  • 67. Setting the Active Class We need to set the class to active if current tab is selected ... index.html </ul> ng-init="tab = 1"> <ul class="nav nav-pills”> >Description</a> >Specifications</a> >Reviews</a> ng-click="tab = 1" ng-click="tab = 2" ng-click="tab = 3" <section <li <li <li > > > <a href <a href <a href </li> </li> </li>
  • 68. The ng-class directive Name of the class to set. Expression to evaluate If true, set class to “active”, otherwise nothing. index.html ng-init="tab = 1"><section <ul class="nav nav-pills”> <li <li <li ng-click="tab = 1" ng-click="tab = 2" ng-click="tab = 3" >Description</a> >Specifications</a> >Reviews</a> </li> </li> </li> </ul> . . . > > > ng-class="{ active:tab === 1 }" ng-class="{ active:tab === 2 }" ng-class="{ active:tab === 3 }" <a href <a href <a href
  • 69.
  • 70. Feels dirty, doesn’t it? All our application’s logic is inside our HTML. How might we pull this logic into a Controller? index.html <section <ul class="nav nav-pills"> <li > <a href >Description</a> <li </li> > <a href >Specifications</a> <li </li> > <a href >Reviews</a> </li> </ul> ng-click=" "tab = 1 "tab = 2ng-click=" ng-click=" "tab = 3 ng-class="{ active: }">tab === 1 ng-class="{ active: }">tab === 2 ng-class="{ active: }">tab === 3 <div class="panel" ng-show=" <h4>Description </h4>
 <p>{{product.description}}</p>
 </div> … tab === 1"> ng-init="tab = 1">
  • 71. Creating our Panel Controller index.html app.js ng-init="tab = 1"<section <ul class="nav nav-pills"> <li > <a href >Description</a> <li </li> > <a href >Specifications</a> <li </li> > <a href >Reviews</a> </li> </ul> ng-controller="PanelController as panel" app.controller("PanelController", function(){ }); ng-click=" "tab = 1 "tab = 2ng-click=" ng-click=" "tab = 3 <li ng-class="{ active: }">tab === 1 <li ng-class="{ active: }">tab === 2 <li ng-class="{ active: }">tab === 3 <div class="panel" ng-show=" <h4>Description </h4>
 <p>{{product.description}}</p>
 </div> … tab === 1"> >
  • 72. Moving our tab initializer index.html app.js <section <ul class="nav nav-pills"> <li > <a href >Description</a> <li </li> > <a href >Specifications</a> <li </li> > <a href >Reviews</a> </li> </ul> app.controller("PanelController", function(){ }); this.tab = 1; <a href ng-click=" "tab = 1 <a href ng-click=" "tab = 2 <a href ng-click=" "tab = 3 <li ng-class="{ active: }">tab === 1 <li ng-class="{ active: }">tab === 2 <li ng-class="{ active: }">tab === 3 <div class="panel" ng-show=" <h4>Description </h4>
 <p>{{product.description}}</p>
 </div> … tab === 1"> ng-controller="PanelController as panel" >
  • 73. Creating our selectTab function index.html app.js <section <ul class="nav nav-pills"> ng-controller="PanelController as panel"> <li > <a href ng-click="panel.selectTab(1) >Description</a>" <li </li> > <a href >Specifications</a>ng-click="panel.selectTab(2)" </li> <li > <a href ng-click="panel.selectTab(3) >Reviews</a> </li> </ul> " app.controller("PanelController", function(){ }); this.tab = 1; ng-class="{ active: ng-class="{ active: ng-class="{ active: }"> }"> }"> tab === 1 tab === 2 tab === 3 <div class="panel" ng-show=" <h4>Description </h4>
 <p>{{product.description}}</p>
 </div> … tab === 1"> this.tab = setTab; }; function(setTab) {this.selectTab =
  • 74. Creating our isSelected function index.html app.js <section <ul class="nav nav-pills"> ng-controller="PanelController as panel"> <li ng-class="{ active: ng-class="{ active: ng-class="{ active: panel.isSelected(1) panel.isSelected(2) panel.isSelected(3) }"> }"> }"> <a href ng-click="panel.selectTab(1) >Description</a>" <a href >Specifications</a>ng-click="panel.selectTab(2)" <a href ng-click="panel.selectTab(3) >Reviews</a>" </li> </ul> panel.isSelected(1)<div class="panel" ng-show=" "> <h4>Description </h4>
 <p>{{product.description}}</p>
 </div> … </li> <li </li> <li <li </li> app.controller("PanelController", function(){ }); this.tab = 1; this.isSelected = function(checkTab){ return this.tab === checkTab; }; this.tab = setTab; }; function(setTab) {this.selectTab =
  • 75.
  • 77.
  • 78.
  • 79. Shaping Up with Angular Level 3: Forms, Models, and Validations
  • 80. More Directives: Forms & Models How can I let my users add content?
  • 81. Adding reviews to our products app.js app.controller("StoreController", function(){
 this.products = [
 { 
 name: 'Awesome Multi-touch Keyboard', 
 price: 250.00,
 description: "...",
 images: [...],
 reviews: [
 { 
 stars: 5,
 body: "I love this product!",
 author: "joe@thomas.com"
 },
 { 
 stars: 1,
 body: "This product sucks",
 author: "tim@hater.com"
 }
 . . .
  • 82. <li class="list-group-item" ng-repeat="product in store.products">
 . . .
 <div class="panel" ng-show="panel.isSelected(3)">
 <h4> Reviews </h4>
 
 <blockquote ng-repeat="review in product.reviews">
 <b>Stars: {{review.stars}}</b>
 {{review.body}} 
 <cite>by: {{review.author}}</cite> 
 </blockquote>
 </div>
 Looping Over Reviews in our Tab index.html
  • 83. We’re displaying Reviews! Nothing new here, but how do we start to implement forms?
  • 84. <h4> Reviews </h4>
 
 <blockquote ng-repeat="review in product.reviews">...</blockquote> Writing out our Review Form index.html <form name="reviewForm"> <select <option value="1">1 star</option>
 <option value="2">2 stars</option>
 . . .
 </select> <textarea></textarea> <label>by:</label> <input type="email" /> <input type="submit" value="Submit" />
 </form> >
  • 85. With Live Preview,. index.html <blockquote> <b>Stars: {{review.stars}}</b>
 {{review.body}} 
 <cite>by: {{review.author}}</cite> 
 </blockquote> How do we bind this review object to the form? <option value="1">1 star</option>
 <option value="2">2 stars</option>
 . . .
 </select> <textarea></textarea> <label>by:</label> <input type="email" /> <input type="submit" value="Submit" />
 </form> <select> <form name="reviewForm">
  • 86. Introducing ng-model&, index.html ng-model="review.stars" ng-model="review.body" ng-model="review.author" <select > <option value="1">1 star</option>
 <option value="2">2 stars</option>
 . . .
 </select> <textarea ></textarea> <label>by:</label> <input type="email" /> <input type="submit" value="Submit" />
 </form> <form name="reviewForm"> <blockquote> <b>Stars: {{review.stars}}</b>
 {{review.body}} 
 <cite>by: {{review.author}}</cite> 
 </blockquote> ng-model binds the form element value to the property
  • 87. Live Preview In Action But how do we actually add the new review?
  • 88. <input ng-model="review.terms" type="checkbox" /> I agree to the terms Two More Binding Examples With a Checkbox With Radio Buttons Sets value to true or false Sets the proper value based on which is selected What color would you like? 
 
 <input ng-model="review.color" type="radio" value="red" /> Red 
 <input ng-model="review.color" type="radio" value="blue" /> Blue 
 <input ng-model="review.color" type="radio" value="green" /> Green

  • 90. We need to Initialize the Review index.html We could do ng-init, but we’re better off creating a controller. <label>by:</label> 
 <input ng-model="review.author" type="email" />
 <input type="submit" value="Submit" />
 </form> <form name="reviewForm"> <b>Stars: {{review.stars}}</b> {{review.body}} <cite>by: {{review.author}}</cite> </blockquote> <blockquote> <select ng-model="review.stars"> <option value="1">1 star</option>
 <option value="2">2 stars</option>
 . . .
 </select> <textarea ng-model="review.body"></textarea>
  • 91. Creating the Review Controller& app.js Now we need to update all the Expressions to use this controller alias. index.html ng-controller="ReviewController as reviewCtrl"<form name="reviewForm" > <b>Stars: {{review.stars}}</b> {{review.body}} <cite>by: {{review.author}}</cite> </blockquote> <select ng-model="review.stars"> <option value="1">1 star</option>
 <option value="2">2 stars</option>
 . . .
 </select> <textarea ng-model="review.body"></textarea> <blockquote> app.controller("ReviewController", function(){
 this.review = {}; });
  • 92. Using the reviewCtrl.review app.js index.html ng-controller="ReviewController as reviewCtrl" reviewCtrl. reviewCtrl. reviewCtrl. reviewCtrl. reviewCtrl. <form name="reviewForm" > <blockquote> <b>Stars: {{ review.stars}}</b> {{ review.body}} <cite>by: {{ review.author}}</cite> </blockquote> <select ng-model=" review.stars"> <option value="1">1 star</option>
 <option value="2">2 stars</option>
 . . .
 </select> <textarea ng-model=" review.body"></textarea> app.controller("ReviewController", function(){
 this.review = {}; });
  • 93. Using ng-submit to make the Form Work^ app.js index.html ng-submit="reviewCtrl.addReview(product)" We need to define this function. ng-submit allows us to call a function when the form is submitted. app.controller("ReviewController", function(){
 this.review = {}; }); reviewCtrl. reviewCtrl. reviewCtrl. ng-controller="ReviewController as reviewCtrl"<form name="reviewForm" <blockquote> <b>Stars: {{ review.stars}}</b> {{ review.body}} <cite>by: {{ review.author}}</cite> </blockquote> >
  • 94. reviewCtrl. app.js index.html ng-controller="ReviewController as reviewCtrl" reviewCtrl. reviewCtrl. ng-submit="reviewCtrl.addReview(product)" Push review onto this product’s reviews array. app.controller("ReviewController", function(){
 this.review = {}; }); this.addReview = function(product) { product.reviews.push(this.review); }; <form name="reviewForm" <blockquote> <b>Stars: {{ review.stars}}</b> {{ review.body}} <cite>by: {{ review.author}}</cite> </blockquote> Using ng-submit to make the Form Work^
  • 95. Now with Reviews! Review gets added, but the form still has all previous values!
  • 96. <form name="reviewForm" ng-controller="ReviewController as reviewCtrl" ng-submit="reviewCtrl.addReview(product)"> <blockquote> <b>Stars: {{reviewCtrl.review.stars}}</b> {{reviewCtrl.review.body}} <cite>by: {{reviewCtrl.review.author}}</cite> </blockquote> Resetting the Form on Submit app.js index.html Clear out the review, so the form will reset. app.controller("ReviewController", function(){
 this.review = {}; }); this.addReview = function(product) { product.reviews.push(this.review); }; this.review = {};
  • 97. This Time the Form Resets However, if we refresh, the reviews get reset!
 We’re not saving the reviews anywhere yet...
  • 99. Turns out Angular has some great client side validations we can use with our directives. What about validations?
  • 100. Our Old Form Code index.html <form name="reviewForm" ng-controller="ReviewController as reviewCtrl" ng-submit="reviewCtrl.addReview(product)"> <select ng-model="reviewCtrl.review.stars" <option value="1">1 star</option>
 ...
 </select> <textarea name="body" ng-model="reviewCtrl.review.body"></textarea> <label>by:</label> <input name="author" ng-model="reviewCtrl.review.author" type="email" /> <input type="submit" value="Submit" />
 </form> >
  • 101. Now with validation. index.html required novalidate required required Turn Off Default HTML Validation Mark Required Fields Print Forms Validity<div> reviewForm is {{reviewForm.$valid}} </div> <form name="reviewForm" ng-controller="ReviewController as reviewCtrl" ng-submit="reviewCtrl.addReview(product)" > <select ng-model="reviewCtrl.review.stars" <option value="1">1 star</option>
 ...
 </select> > <textarea name="body" ng-model="reviewCtrl.review.body" ></textarea> <label>by:</label> <input name="author" ng-model="reviewCtrl.review.author" type="email" /> <input type="submit" value="Submit" />
 </form>
  • 102. With validations We don’t want the form to submit when it’s invalid.
  • 103. <form name="reviewForm" ng-controller="ReviewController as reviewCtrl" ng-submit="reviewCtrl.addReview(product)" novalidate> Preventing the Submit index.html We only want this method to be called if reviewForm.$valid is true.
  • 104. <form name="reviewForm" ng-controller="ReviewController as reviewCtrl" ng-submit="reviewForm.$valid && reviewCtrl.addReview(product)" novalidate> Preventing the Submit index.html If valid is false, then addReview is never called.
  • 105. Doesn’t Submit an Invalid Form How might we give a hint to the user why their form is invalid?
  • 106. The Input Classes index.html Source before typing email <input name="author" ng-model="reviewCtrl.review.author" type="email" required /> <input name="author" . . . class="ng-pristine ng-invalid"> Source after typing, with invalid email <input name="author". . . class="ng-dirty ng-invalid"> Source after typing, with valid email <input name="author" . . . class="ng-dirty ng-valid"> So, let’s highlight the form field using classes after we start typing, showing if a field is valid or invalid. ng-valid ng-invalid ng-dirty
  • 107. .ng-invalid.ng-dirty {
 border-color: #FA787E;
 } ! .ng-valid.ng-dirty {
 border-color: #78FA89;
 } The classes index.html style.css Red border for invalid Green border for valid <input name="author" ng-model="reviewCtrl.review.author" type="email" required />
  • 108. Now with red and green borders!
  • 109. Web forms usually have rules around valid input: • Angular JS has built-in validations for common input types: HTML5-based type validations <input type="email" name="email"> min=1 max=10 Can also define min & max with numbers <input type="url" name="homepage"> <input type="number" name="quantity">
  • 110.
  • 111.
  • 112. Shaping Up with Angular JS Level 4: Creating a Directive with an Associated Controller
  • 113. Decluttering our Code index.html We’re going to have multiple pages that want to reuse this HTML snippet. How do we eliminate this duplication? <ul class="list-group">
 <li class="list-group-item" ng-repeat="product in store.products"> <h3> {{product.name}} 
 <em class="pull-right">${{product.price}}</em> </h3> <section ng-controller="PanelController as panel"> . . .
  • 114. Using ng-include for Templates index.html product-title.html <h3 ng-include="'product-title.html'" class="ng-scope">
 <span class="ng-scope ng-binding">Awesome Multi-touch Keyboard</span>
 <em class="pull-right ng-scope ng-binding">$250.00</em>
 </h3> generated html ng-include is expecting a variable with the name of the file to include.
 To pass the name directly as a string, use single quotes ('...') <ul class="list-group">
 <li class="list-group-item" ng-repeat="product in store.products"> <h3 name of file to includeng-include="'product-title.html'" </h3> <section ng-controller="PanelController as panel"> > {{product.name}} 
 <em class="pull-right">${{product.price}}</em>
  • 115.
  • 116. Web Server HTML JavaScript Response with Webpage & Assets Web Browser URL Request to server HTML Returned Fetches ng-included file HTML Browser loads up Angular app.
  • 117. <h3 ng-include="'product-title.html'"></h3> Creating our First Custom Directive index.html Custom Directive Using ng-include... Our old code and our custom Directive will do the same thing... with some additional code. <product-title></product-title> index.html Why write a Directive?
  • 118. Why Directives? Directives allow you to write HTML that expresses the behavior of your application. Can you tell what this does?<aside class="col-sm-3">
 <book-cover></book-cover>
 <h4><book-rating></book-rating></h4>
 </aside>
 
 <div class="col-sm-9">
 <h3><book-title></book-title></h3>
 
 <book-authors></book-authors>
 
 <book-review-text></book-review-text>
 
 <book-genres></book-genres>
 </div>
  • 119. Template-expanding Directives are the simplest: • define a custom tag or attribute that is expanded or replaced • can include Controller logic, if needed Writing Custom Directives Directives can also be used for: •Expressing complex UI •Calling events and registering event handlers •Reusing common components
  • 120. app.directive('productTitle', function(){
 return { ! };
 }); How to Build Custom Directives app.js <product-title></product-title> index.html A configuration object defining how your directive will work
  • 121. app.directive('productTitle', function(){
 return { ! ! };
 }); How to Build Custom Directives app.js <product-title></product-title> index.html <h3>
 {{product.name}}
 <em class="pull-right">$250.00</em>
 </h3> index.html Type of Directive
 (E for Element) Url of a template generates into restrict: 'E', templateUrl: 'product-title.html' camelCase in JavaScriptdash in HTML translates to ...
  • 122.
  • 123. index.html Attribute vs Element Directives Element Directive Attribute Directive …some browsers don’t like self-closing tags. Use Element Directives for UI widgets and Attribute Directives for mixin behaviors... like a tooltip. index.html Notice we’re not using a self-closing tag… <product-title></product-title> <h3 product-title></h3> <product-title/>
  • 124. index.html Defining an Attribute Directive app.js <h3>
 {{product.name}}
 <em class="pull-right">$250.00</em>
 </h3> index.html generates into <h3 product-title></h3> app.directive('productTitle', function(){
 return { ! 
 };
 }); Though normally attributes would be for mixin behaviors ... restrict: 'A', templateUrl: 'product-title.html' Type of Directive
 (A for Attribute)
  • 125. When you think of a dynamic web application, do you think you’ll be able to understand the functionality just by looking at the HTML? Directives allow you to write better HTML When you're writing an Angular JS application, you should be able to understand the behavior and intent from just the HTML. No, right? And you’re likely using custom directives to write expressive HTML.
  • 126. Shaping Up with Angular JS Creating Our Own Directives
  • 127. <h3> 
 {{product.name}} 
 <em class="pull-right">${{product.price}}</em> </h3> Reviewing our Directive index.html Template-Expanding Directives An Attribute Directive An Element Directive <h3 product-title></h3> <h3> <product-title></product-title> </h3>
  • 128. What if we need a Controller? index.html }Directive? ng-controller="PanelController as panels" <ul class="nav nav-pills"> . . . </ul>
 <div class="panel" ng-show="panels.isSelected(1)"> . . . </div>
 <div class="panel" ng-show="panels.isSelected(2)"> . . . </div>
 <div class="panel" ng-show="panels.isSelected(3)"> . . . </div> </section> ><section
  • 129. First, extract the template... product-panels.html index.html ><section <ul class="nav nav-pills"> . . . </ul>
 <div class="panel" ng-show="panels.isSelected(1)"> . . . </div>
 <div class="panel" ng-show="panels.isSelected(2)"> . . . </div>
 <div class="panel" ng-show="panels.isSelected(3)"> . . . </div> </section> <h3> <product-title> </h3> ng-controller="PanelController as panels" . . . </product-panels> <product-panels >
  • 130. Now write the Directive ... app.js index.html ng-controller="PanelController as panels" . . . </product-panels> <product-panels > app.directive('productPanels', function(){
 return { restrict: 'E', templateUrl: 'product-panels.html' };
 });
  • 131. What about the Controller? app.js index.html ng-controller="PanelController as panels" . . . </product-panels> <product-panels > app.directive('productPanels', function(){
 return { restrict: 'E', templateUrl: 'product-panels.html' };
 }); app.controller('PanelController', function(){ . . . }); First we need to move the functionality inside the directive
  • 132. Moving the Controller Inside app.js index.html ng-controller="PanelController as panels" . . . </product-panels> <product-panels > app.directive('productPanels', function(){
 return { restrict: 'E', templateUrl: 'product-panels.html' };
 }); , Next, move the alias inside function(){ . . . controller: }
  • 133. Need to Specify the Alias app.js index.html Now it works, using panels as our Controller Alias. . . . </product-panels> <product-panels> controllerAs: 'panels' }; }); app.directive('productPanels', function(){
 return { restrict: 'E', templateUrl: 'product-panels.html' };
 }); , , function(){ . . . controller: }
  • 134.
  • 136.
  • 137.
  • 138. Shaping Up with Angular JS Level 5: Dependencies and Services
  • 139. (function(){
 var app = angular.module('store', [ Starting to get a bit cluttered? app.js Can we refactor these out? . . .
 })(); app.controller('StoreController', function(){ . . . }); ]); app.directive('productTitle', function(){ . . . }); ! app.directive('productGallery', function(){ . . . }); ! app.directive('productPanels', function(){ . . . });
  • 140. (function(){
 var app = angular.module('store', [ Extract into a new file ... products.js app.js . . .
 })(); app.controller('StoreController', function(){ . . . }); ]); products.js app.directive('productTitle', function(){ . . . }); ! app.directive('productGallery', function(){ . . . }); ! app.directive('productPanels', function(){ . . . });
  • 141. (function(){
 var app = angular.module('store', [ Make a new Module app.js . . .
 })(); app.controller('StoreController', function(){ . . . }); ]); products.js (function(){
 var app = angular.module('store })(); -products', [ ]); Define a new module just for Product stuff... Module Name Different closure means different app variable. app.directive('productTitle', function(){ . . . }); ! app.directive('productGallery', function(){ . . . }); ! app.directive('productPanels', function(){ . . . });
  • 142. (function(){
 var app = angular.module('store', [ Add it to the dependencies ... app.js . . .
 })(); app.controller('StoreController', function(){ . . . }); ]); app.directive('productTitle', function(){ . . . }); app.directive('productGallery', function(){ . . . }); app.directive('productPanels', function(){ . . . }); products.js (function(){
 var app = angular.module('store })(); -products', [ ]); 'store-products' Module Name store depends on store-products
  • 143. <!DOCTYPE html>
 <html ng-app="store">
 <head> . . . </head>
 <body ng-controller="StoreController as store">
 . . .
 <script src="angular.js"></script>
 <script src="app.js"></script> We’ll also need to include the file index.html </body>
 </html> <script src="products.js"></script>

  • 144.
  • 145. Best to split Modules around functionality: • app.js – top-level module attached via ng-app • products.js – all the functionality for products and only products How should I organize my application Modules?
  • 147. Does this feel strange? app.js What is all this data doing here? Where can we put it? Shouldn't we fetch this from an API? (function(){
 var app = angular.module('store', [ 'store-products' ]);
 
 app.controller('StoreController', function(){
 this.products = [ { name: '. . .', price: 1.99, . . . },
 { name: '. . .', price: 1.99, . . . },
 { name: '. . .', price: 1.99, . . . }, . . . 
 });
 })(); . . .
 ];
  • 148. How do we get that data? app.js How do we fetch our products from an API? http://api.example.com/products.json (function(){
 var app = angular.module('store', [ 'store-products' ]);
 
 app.controller('StoreController', function(){
 this.products = ???; . . . 
 });
 })(); { name: '. . .', price: 1.99, . . . },
 { name: '. . .', price: 1.99, . . . },
 { name: '. . .', price: 1.99, . . . }, [ . . .
 ]
  • 149. Services give your Controller additional functionality, like ... • Fetching JSON data from a web service with $http • Logging messages to the JavaScript console with $log • Filtering an array with $filter We need a Service! All built-in Services start with a $ sign ...
  • 150. The $http Service is how we make an async request to a server ... • By using $http as a function with an options object: Introducing the $http Service! So how do we use it? $http({ method: 'GET', url: '/products.json' }); • Or using one of the shortcut methods: $http.get('/products.json', { apiKey: 'myApiKey' }); • Both return a Promise object with .success() and .error() • If we tell $http to fetch JSON, the result will be automatically decoded into JavaScript objects and arrays
  • 151. Use this funky array syntax: app.controller('SomeController', [ '$http', function($http){
 
 } ]); How does a Controller use a Service like $http? Service name Service name as an argument Dependency Injection! app.controller('SomeController', [ '$http', '$log', function($http, $log){
 
 } ]); If you needed more than one
  • 152. When Angular is Loaded Services are Registered SomeController $http Injector $log app.controller('SomeController', [ '$http', '$log', function($http, $log){
 
 } ]);
  • 153. app.controller('SomeController', [ '$http', '$log', function($http, $log){
 
 } ]); A Controller is Initialized SomeController $http Injector $log and $log, too ... I need $http ... Psst... When I run...
  • 154. app.controller('SomeController', [ '$http', '$log', function($http, $log){
 
 } ]); Then When the Controller runs ... SomeController $http Injector $log Here ya go! Dependency Injection!
  • 155. (function(){
 var app = angular.module('store', [ 'store-products' ]);
 
 app.controller('StoreController', So where were we? app.js ){function( this.products = ???; );} })();
  • 156. (function(){
 var app = angular.module('store', [ 'store-products' ]);
 
 app.controller('StoreController', Time for your injection! app.js ){function( this.products = ???; );} })(); [ '$http', StoreController needs the $http Service... ...so $http gets injected as an argument! Now what? $http ]
  • 157. (function(){
 var app = angular.module('store', [ 'store-products' ]);
 
 app.controller('StoreController', Let’s use our Service! app.js ){function( this.products = ???; );} })(); [ '$http', $http $http.get('/products.json') Fetch the contents of products.json... ]
  • 158. (function(){
 var app = angular.module('store', [ 'store-products' ]);
 
 app.controller('StoreController', Our Service will Return Data app.js ){function( this.products = ???; );} })(); [ '$http', $http $http.get('/products.json').success(function(data){ ??? }); = data; $http returns a Promise, so success() gets the data... What do we assign data to, though...? ]
  • 159. (function(){
 var app = angular.module('store', [ 'store-products' ]);
 
 app.controller('StoreController', Storing the Data for use in our Page app.js ){function( );} })(); [ '$http', $http $http.get('/products.json').success(function(data){ }); = data; var store = this; store.products We need to store what this is ... ... and now we have somewhere 
 to put our data! But the page might look funny until the data loads. ]
  • 160. (function(){
 var app = angular.module('store', [ 'store-products' ]);
 
 app.controller('StoreController', Initialize Products to be a Blank Array app.js ){function( );} })(); [ '$http', $http $http.get('/products.json').success(function(data){ }); = data; var store = this; store.products store.products = [ ]; We need to initialize products to an empty array, since the page will render before our data returns from our get request. ]
  • 161.
  • 162. $http.post('/path/to/resource.json', { param: 'value' }); Additional $http functionality $http({ method: 'PATCH', url: '/path/to/resource.json' }); $http({ method: 'TRACE', url: '/path/to/resource.json' }); In addition to get() requests, $http can post(), put(), delete()... $http.delete('/path/to/resource.json'); $http({ method: 'OPTIONS', url: '/path/to/resource.json' }); ...or any other HTTP method by using a config object: