SlideShare a Scribd company logo
ANGULARJS
INTRODUCTIONby @DanielPerez ClaudeTech
LEAVES
STATIC WEBSITE BUILD TOOL
Dependsonly onNodeJS.
Uses:
Yeoman
Grunt
Bower
Jade(or EJS)
Stylus(or lessor plainCSS)
Coffee(or plainJS)
Installwith:
$npminstall-gleaves
$leavessetup
Checkout for moreinfo.thedocs
PROJECT CREATION
$leavesnewangular-blog
$cdangular-blog
$leavesinstalljqueryangularangular-resourcebootstrapangular-ui-routermarkdown
Renameassets/js/app.coffeetoassets/js/app.js,
eraseassets/css/main.stylcontent andedit views/layout.jade.
//views/layout.jade
html
head
....
link(rel="stylesheet"href="components/bootstrap/dist/css/bootstrap.min.css")
link(rel="stylesheet"href="components/bootstrap/dist/css/bootstrap-theme.min.css")
script(src="components/jquery/dist/jquery.min.js")
script(src="components/angular/angular.min.js")
script(src="components/angular-resource/angular-resource.min.js")
script(src="components/angular-ui-router/release/angular-ui-router.min.js")
script(src="components/bootstrap/dist/js/bootstrap.min.js")
script(src="js/app.js")
body
blockcontent
START HACKING
Whenyouaredonewithbasic setup,run
$leaves
andstart hacking.
FOR SCEPTICAL PEOPLE
If youdonot want touseleaves,check about basic Angular setup.my blog post
TRY ANGULARJS
Initializeapplication
//views/layout.jade
html
head
...
body(ng-app="")
blockcontent
Try two-way databinding:
Output variablevaluewith: {{variable}}.
Changevariablevaluewith: ng-model="variable"
//views/index.jade
extends./layout.jade
blockcontent
input(ng-model="variable")
span{{variable}}
TRY ANGULARJS
Initializevariable:
//views/index.jade
extends./layout.jade
blockcontent
div(ng-init="variable='plaintext'")
span{{variable}}
Youcanuseany element,not just divandspan.
TRY ANGULARJS
Usecontroller toinitializevariable.
//views/index.jade
div(ng-controller="TestCtrl")
span{{variable}}
Definecontroller inJS file.
$scopeisinjectedby Angular oninstanciation.
//assets/js/app.js
functionTestCtrl($scope){
$scope.variable="myvariabletext";
}
Angular uses toinstanciatecontrollers,services,etc.DI
TRY ANGULARJS
React toevents:
//views/index.jade
div(ng-controller="TestCtrl")
span{{variable}}
button(ng-click="action()")
//assets/js/app.js
functionTestCtrl($scope){
$scope.variable="myvariabletext";
$scope.action=function(){
$scope.variable="Ijustclicked!";
};
}
CREATE BLOG
Createblog withfollowing functionalities:
List posts
List postsby category
Showpost
Createnewpost
WewillusepreparedAPI toworkwith.
Authentication/authorizationwillbefor next time.
Sampleisavailableat .angular-blog-sample.herokuapp.com
Fullsourcecodeisavailableat
.
github.com/claudetech-meetups/angular-blog-
sample
AVAILABLE API
TheavailableAPI callsare
GET /posts
GET /posts/:id
POST /posts
GET /categories
POST /categories
API isavailableat: http://angular-tutorial-api.herokuapp.com/
CREATE BASIC LAYOUT
Addheader toviews/layout.jade
html
head
....
body(ng-app="")
.container
nav.navbar.navbar-default
.container-fluid
.navbar-header
a.navbar-brand(href="#")Blog
.row
.col-xs-8
blockcontent
.col-xs-4
.block.categories
h3Categories
ul.list-unstyled
li:a.small(href="#")Plentyofcategories
.block.admin
h3Admin
ul.list-unstyled
li:a.small(href="#")Addpost
CREATE BASIC LAYOUT
Createempty views/posts/index.jadeandedit views/index.jade.
//views/index.jade
extends./layout.jade
blockcontent
include./posts/index
BUILD POST LIST
Createcontroller inJS file:
functionPostIndexCtrl($scope){
$scope.post={
id:1,
title:"Posttitle",
content:"Postcontent",
createdAt:newDate()
};
}
Wrappost list inacontroller andusedummy data
.posts(ng-controller="PostIndexCtrl")
.post.row
.row
.col-xs-12
h2{{post.title}}
small.date{{post.createdAt}}
.row.content
.col-xs-12{{post.content}}
.row
.col-xs-12
a.small(href="#")Seemore
andcreatethecontroller.
SOME ISSUES
{{variable}}appearsonpageload
Dateformat isstrange
Nolinebreakincontent
Content may bevery long
SOME SOLUTIONS
Useng-bindinsteadof {{}}
Usedatefilter
Wewillseehowtorender markdownincontent later on
UselimitTofilter
.posts(ng-controller="PostIndexCtrl")
.post.row
.row
.col-xs-12
h2(ng-bind="post.title")
small.date(ng-bind="post.createAt|date:'y/M/d'")
.row.content
.col-xs-12(ng-bind="post.content|limitTo:100")
.row
.col-xs-12
a.small(href="#")Seemore
MAKE IT A LIST
Adddummy datainthecontroller.
functionPostIndexCtrl($scope){
$scope.posts=[{
id:1,
title:"Posttitle",
content:"Postcontent",
createdAt:newDate()
},{
id:2,
title:"Posttitle2",
content:"Postcontent2",
createdAt:newDate()
}];
}
Useng-repeat
.posts(ng-controller="PostIndexCtrl")
.post.row(ng-repeat="postinposts")
...
SHOW SINGLE POST
Createviews/posts_show.jade,wewillextendlayout.jadefor now.
extends./layout.jade
blockcontent
.post.row(ng-controller="PostShowCtrl")
.row
.col-xs-12
h2{{post.title}}
small.date{{post.createdAt|date:'y/M/d'}}
.row.content
.col-xs-12{{post.content}}
createPostShowCtrlfunction.
//assets/js/app.js
....
functionPostShowCtrl($scope){
$scope.post={
id:1,
title:"Posttitle",
content:"Postcontent",
createdAt:newDate()
};
}
Youcantry toaccessyour page: localhost:9000/posts_show.html
SOME ISSUES
Better modularizecontrollers
Wedon't want another page
Wewant content inmarkdown
MODULARIZATION
Let'sstart by splitting files.
//assets/js/controllers/posts/index.js
functionPostIndexCtrl($scope){
.....
}
//assets/js/controllers/posts/show.js
functionPostShowCtrl($scope){
.....
}
//views/layout.jade
html
head
....
script(src="js/app.js")
script(src="js/controllers/posts/index.js")
script(src="js/controllers/posts/show.js")
body(ng-app="")
...
ANGULAR MODULES
Angular hasnativemodules.DeclareBlogAppmodulewithnodepencies.
//assets/js/app.js
angular.module('BlogApp',[]);
Declarecontrollersaspart of themodule.
//assets/js/controllers/posts/index.js
angular.module('BlogApp').controller('PostIndexCtrl',[
'$scope',function($scope){
...
}
]);
Samegoesfor PostShowCtrl.
ROUTING
Routeinorder tobeabletohave
/#/->allposts
/#/posts/:id->post withid=:id
/#/posts/new->newpost
First,add depency tothemodule.ui.router
//assets/js/app.js
angular.module('BlogApp',[
'ui.router'
]);
SETUP VIEW
First,addtheviewwheretodisplay thecontent of theroute.
//views/index.jade
extends./layout.jade
blockcontent
div(ui-view)
SETUP ROUTER
Configuretoredirect to/whennoroutefound,andconfiguretheroutes.
//assets/js/app.js
...
angular.module('BlogApp').config([
'$stateProvider','$urlRouterProvider',function($stateProvider,$urlRouterProvider){
$urlRouterProvider.otherwise('/');
$stateProvider
.state('index',{
url:'/',
templateUrl:'posts/index.html'
})
.state('show',{
url:'/posts/:id',
templateUrl:'posts/show.html'
});
}
]);
Then,removetheextendsandblockcontentfrom
views/posts_show.jade: wedon't needthewholelayout.For consistency,
moveviews/post_show.jadetoviews/posts/show.jade.
Youcannowaccessyour route: localhost:9000/#/posts/1
SETUP ROUTER
Controllersshouldbedefinedinroutes.
//assets/js/app.js
.state('index',{
url:'/',
templateUrl:'posts/index.html',
controller:'PostIndexCtrl'
})
.state('show',{
url:'/posts/:id',
templateUrl:'posts/show.html',
controller:'PostShowCtrl'
});
andremovedfromviews/posts/index.jadeand
views/posts/show.jade.
//views/posts/show.jade
.post.row//nong-controlleranymore
...
ADD LINKS
usesui-sreftomakelinkinsteadof normalhrefor ng-href
attributes.
ui-router
//views/posts/index.jade
...
a.small(ui-sref="show({id:post.id})")Seemore
USE API
AddngResourcemoduleasadependency.
//assets/js/app.js
angular.module('BlogApp',[
'ui.router',
'ngResource'
]);
...
Try it
//assets/js/controllers/posts/index.js
angular.module('BlogApp').controller('PostIndexCtrl',[
'$scope','$resource',function($scope,$resource){
//noneedfordummydataanymore
varPost=$resource('http://angular-tutorial-api.herokuapp.com/posts/:id');
Post.query(function(posts){
console.log(posts[0]);
$scope.posts=posts;
});
}
]);
RESOURCE FACTORY
Wewant tobeabletousePostresourceanywhere.
Let'smakeit afactory.
//assets/js/resources/post.js
angular.module('BlogApp').factory('Post',[
'$resource',function($resource){
return$resource('http://angular-tutorial-api.herokuapp.com/posts/:id');
}
]);
andincludeit inviews/layout.jade
html
head
...
script(src="js/resources/post.js")
USE RESOURCE FACTORY
//assets/js/controllers/index.js
angular.module('BlogApp').controller('PostIndexCtrl',[
'$scope','Post',function($scope,Post){
Post.query(function(posts){
$scope.posts=posts;
});
}
]);
FETCH SINGLE POST
Use$stateParamstoget id,andget post fromserver.
//assets/js/controllers/posts/show.js
angular.module('BlogApp').controller('PostShowCtrl',[
'$scope','$stateParams','Post',function($scope,$stateParams,Post){
Post.get({id:$stateParams.id},function(post){
$scope.post=post;
});
}
]);
CREATE CATEGORY FACTORY
//assets/js/resources/category.js
angular.module('BlogApp').factory('Category',[
'$resource',function($resource){
return$resource('http://angular-tutorial-api.herokuapp.com/categories/:id');
}
]);
andaddit tolayout.jade
NEW POST CONTROLLER
CreatenewJS file,andafreshpost tobind.
//assets/js/controllers/posts/new.js
angular.module('BlogApp').controller('PostNewCtrl',[
'$scope','Post',function($scope,Post){
$scope.post=newPost();
}
]);
andincludeit inviews/layout.jade
script(src="js/controllers/posts/new.js")
CREATE NEW POST TEMPLATE
Bindthemodelcreatedinthecontroller.
//views/posts/new.jade
h2Createnewpost
form
.form-group
label(for="title")Title
input#title.form-control(type="text"placeholder="Title"ng-model="post.title")
.form-group
label(for="content")Content
textarea#content.form-control(rows="10"ng-model="post.content")
.form-group
select.form-control(ng-model="post.category_id")
input.btn.btn-default(type="submit"value="Create")
ADD A NEW ROUTE
Careful,order matters!
$stateProvider
.state('index',{
.....
})
.state('new',{
url:'/posts/new',
templateUrl:'posts/new.html',
controller:'PostNewCtrl'
})
.state('show',{
.....
});
Andset link
//views/layout.jade
...
.block.admin
h3Admin
ul.list-unstyled
li:a.small(ui-sref="new")Addpost
RESOLVE CATEGORIES
Better havecategoriesbeforeloading template.Usecustommadepromiseand
resolveAPI result.
//assets/js/app.js
...
.state('new',{
url:'/posts/new',
templateUrl:'posts/new.html',
controller:'PostNewCtrl',
resolve:{
categories:['$q','Category',function($q,Category){
vardeferred=$q.defer();
Category.query(function(categories){
deferred.resolve(categories);
});
returndeferred.promise;
}]
}
})
.state('show',{
....
RESOLVE CATEGORIES
Usethecategoriesresolvedinthecontroller.
//assets/js/controllers/posts/new.js
angular.module('BlogApp').controller('PostNewCtrl',[
'$scope','Post','categories',function($scope,Post,categories){
$scope.post=newPost();
$scope.categories=categories;
}
]);
USE NG-OPTIONS
Dynamically showcategoriesinselectusing ng-options.
form
...
select.form-control(
ng-model="post.category_id"
ng-options="c.idasc.nameforcincategories"
)
CREATE POST
React tosubmit event
//views/posts/new.jade
form(ng-submit="createPost()")
Addhandler for submit event.
//js/controllers/posts/new.js
angular.module('BlogApp').controller('PostNewCtrl',[
'$scope','Post','$state','categories',function($scope,Post,$state,categories){
...
$scope.createPost=function(){
$scope.post.$save(function(post){
$state.go('index',{id:post.id});
});
};
...
FORMAT MARKDOWN
Wearegoing tocreateafilter toformat markdown.
//assets/js/filters/markdown.js
angular.module('BlogApp').filter('markdown',[
'$sce',function($sce){
returnfunction(input){
if(!input){
return'';
}
return$sce.trustAsHtml(markdown.toHTML(input));
};
}
]);
inputisthevaluetoconvert tomarkdown.Wereturnempty string if
undefined.
ThemarkdownisformattedinHTML,weneedtotrust theinput totellAngular
it issafe.
DISPLAY FORMATTED
MARKDOWN
Weuseng-bind-htmltodisplay HTML andnot escapedvalues.
//views/posts/show.jade
.post.row
....
.row.content
.col-xs-12(ng-bind-html="post.content|markdown")
CREATE CATEGORIES
CONTROLLER
Asfor posts,query toget allthecategories.
//assets/js/controllers/categories/index.js
angular.module('BlogApp').controller('CategoryIndexCtrl',[
'$scope','Category',function($scope,Category){
Category.query(function(categories){
$scope.categories=categories;
});
}
]);
SHOW CATEGORIES
Createpartial
//views/categories/index.jade
.block.categories(ng-controller="CategoryIndexCtrl")
h3Categories
ul.list-unstyled
li(ng-repeat="categoryincategories")
a.small(ui-sref="index({category:category.id})"ng-bind="category.name")
Changelayout tousepartial.
//views/layout.jade
....
.col-xs-4
include./categories/index
.block.admin
h3Admin
ul.list-unstyled
li:a.small(ui-sref="new")Addpost
UPDATE ROUTES
Updateindex routestotakecategoryquery parameter.
//assets/js/app.js
...
$stateProvider
.state('index',{
url:'/?category',
templateUrl:'posts/index.html',
controller:'PostIndexCtrl'
})
Thisisneededtopasscategorytoui-srefandtoreadit from
$stateParams.
FILTER QUERY
Checkif thereisacategory definedandadapt query.
//assets/js/controllers/posts/index.js
angular.module('BlogApp').controller('PostIndexCtrl',[
'$scope','$stateParams','Post',function($scope,$stateParams,Post){
varsearch=$stateParams.category?{category_id:$stateParams.category}:{};
Post.query(search,function(posts){
$scope.posts=posts;
});
}
]);

More Related Content

PPT
Ionic tabs template explained
PDF
Angular js routing options
PPTX
AngularJS Directives
PDF
Advanced Tips & Tricks for using Angular JS
DOCX
How routing works in angular js
PPTX
Building an End-to-End AngularJS Application
KEY
AngularJS for designers and developers
PPTX
AngularJS Architecture
Ionic tabs template explained
Angular js routing options
AngularJS Directives
Advanced Tips & Tricks for using Angular JS
How routing works in angular js
Building an End-to-End AngularJS Application
AngularJS for designers and developers
AngularJS Architecture

What's hot (20)

PPTX
Practical AngularJS
PPTX
Angular js
ODP
AngularJs Crash Course
PPTX
AngularJS Internal
PDF
[FEConf Korea 2017]Angular 컴포넌트 대화법
PPTX
Introduction to Angularjs
PDF
Get AngularJS Started!
PDF
Sane Async Patterns
PPTX
Why angular js Framework
PDF
Intro to Angular.JS Directives
PDF
AngularJS Basics with Example
PPT
Creating the interfaces of the future with the APIs of today
PPTX
AngularJs
PDF
Using Renderless Components in Vue.js during your software development.
PDF
Building a Startup Stack with AngularJS
PPTX
How to Build SPA with Vue Router 2.0
PPTX
IndexedDB - Querying and Performance
PPTX
The AngularJS way
PDF
Introducing Rendr: Run your Backbone.js apps on the client and server
PDF
Modular and Event-Driven JavaScript
Practical AngularJS
Angular js
AngularJs Crash Course
AngularJS Internal
[FEConf Korea 2017]Angular 컴포넌트 대화법
Introduction to Angularjs
Get AngularJS Started!
Sane Async Patterns
Why angular js Framework
Intro to Angular.JS Directives
AngularJS Basics with Example
Creating the interfaces of the future with the APIs of today
AngularJs
Using Renderless Components in Vue.js during your software development.
Building a Startup Stack with AngularJS
How to Build SPA with Vue Router 2.0
IndexedDB - Querying and Performance
The AngularJS way
Introducing Rendr: Run your Backbone.js apps on the client and server
Modular and Event-Driven JavaScript
Ad

Similar to Angular JS blog tutorial (20)

PDF
Node.js & Twitter Bootstrap Crash Course
PDF
20190118_NetadashiMeetup#8_React2019
PDF
Desenvolvimento web com Ruby on Rails (parte 2)
PDF
jQuery (MeshU)
PDF
jQuery (BostonPHP)
PDF
Styling components with JavaScript
PDF
Webpack packing it all
PDF
Packing it all: JavaScript module bundling from 2000 to now
PDF
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
PDF
Fisl 11 - Dicas de Desenvolvimento Web com Ruby
PDF
Modular Test-driven SPAs with Spring and AngularJS
PDF
Enjoy the vue.js
PPTX
Introduction à AngularJS
PDF
Using RequireJS with CakePHP
PDF
Everything is Awesome - Cutting the Corners off the Web
PDF
Building iPhone Web Apps using "classic" Domino
PDF
Backbone.js — Introduction to client-side JavaScript MVC
KEY
[Coscup 2012] JavascriptMVC
PPTX
PPTX
JavaScript Perfomance
Node.js & Twitter Bootstrap Crash Course
20190118_NetadashiMeetup#8_React2019
Desenvolvimento web com Ruby on Rails (parte 2)
jQuery (MeshU)
jQuery (BostonPHP)
Styling components with JavaScript
Webpack packing it all
Packing it all: JavaScript module bundling from 2000 to now
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
Fisl 11 - Dicas de Desenvolvimento Web com Ruby
Modular Test-driven SPAs with Spring and AngularJS
Enjoy the vue.js
Introduction à AngularJS
Using RequireJS with CakePHP
Everything is Awesome - Cutting the Corners off the Web
Building iPhone Web Apps using "classic" Domino
Backbone.js — Introduction to client-side JavaScript MVC
[Coscup 2012] JavascriptMVC
JavaScript Perfomance
Ad

Recently uploaded (20)

PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
PDF
Event Presentation Google Cloud Next Extended 2025
PPTX
ABU RAUP TUGAS TIK kelas 8 hjhgjhgg.pptx
PDF
Revolutionize Operations with Intelligent IoT Monitoring and Control
PDF
Dell Pro 14 Plus: Be better prepared for what’s coming
PPTX
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Software Development Methodologies in 2025
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
PDF
Enable Enterprise-Ready Security on IBM i Systems.pdf
PDF
Reimagining Insurance: Connected Data for Confident Decisions.pdf
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
PDF
Why Endpoint Security Is Critical in a Remote Work Era?
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
CroxyProxy Instagram Access id login.pptx
PDF
GamePlan Trading System Review: Professional Trader's Honest Take
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
madgavkar20181017ppt McKinsey Presentation.pdf
Event Presentation Google Cloud Next Extended 2025
ABU RAUP TUGAS TIK kelas 8 hjhgjhgg.pptx
Revolutionize Operations with Intelligent IoT Monitoring and Control
Dell Pro 14 Plus: Be better prepared for what’s coming
Telecom Fraud Prevention Guide | Hyperlink InfoSystem
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Software Development Methodologies in 2025
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
Enable Enterprise-Ready Security on IBM i Systems.pdf
Reimagining Insurance: Connected Data for Confident Decisions.pdf
A Day in the Life of Location Data - Turning Where into How.pdf
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Why Endpoint Security Is Critical in a Remote Work Era?
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Understanding_Digital_Forensics_Presentation.pptx
CroxyProxy Instagram Access id login.pptx
GamePlan Trading System Review: Professional Trader's Honest Take
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf

Angular JS blog tutorial