Introduction to AngularJS
-
Upload
yoann-gotthilf -
Category
Software
-
view
1.305 -
download
1
description
Transcript of Introduction to AngularJS
![Page 1: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/1.jpg)
Introduction to
![Page 2: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/2.jpg)
Javascript evolution
1996JavaScript, JScript
1997JavaScript by ECMAScript
~2002Ajax
2005Jquery, Mootools, YUI, Prototype, …
2006GWT, JSF, Ext JS
2009(Node.js)
![Page 3: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/3.jpg)
Javascript evolution
1996JavaScript, JScript
1997JavaScript by ECMAScript
~2002Ajax
2005Jquery, Mootools, YUI, Prototype, …
2006GWT, JSF, Ext JS
2009(Node.js)
… and otherMV* frameworks
![Page 5: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/5.jpg)
What is AngularJS ?
« HTML enhanced for web apps! » https://angularjs.org/
That’s all? … of course not!
![Page 6: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/6.jpg)
About AngularJS
• Created in 2009 at Brat Tech LLC• Developed at Google• Open Source (Licence MIT)• Over 400 contributors• Current version 1.2.25 (1.3 soon & 2.0 later)• Compatibility IE8+• 100Ko
![Page 7: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/7.jpg)
Why AngularJS ?
MVW Framework with :• 2-way data binding• Templating• Dependency injection• Routing• Testability• Modularity
• Community• By Google (?)
![Page 8: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/8.jpg)
Learning curve
![Page 9: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/9.jpg)
AngularJS template concept
<html ng-app><div>
<input type="text" ng-model="name"><p ng-show="name">Hello {{name}}</p>
</div><script src=“scripts/angular.js" >
</html>
![Page 10: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/10.jpg)
Template compilation
![Page 11: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/11.jpg)
AngularJS template demo
Talk is cheap
Show me the code
![Page 12: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/12.jpg)
Expression definition
Expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}
<p>1+2={{1+2}}{{a+b}}{{'Hello '+name}}{{user.name}}{{items[index]}}
</p>
![Page 13: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/13.jpg)
Directive concept
Directives are markers on a DOM element to attach a specified behavior to that DOM element or even transform the DOM element and its children
Directives can be an attribute, element name, comment or CSS class.
<html ng-app><div>
<input type="text" ng-model="name"><p ng-show="name">Hello {{name}}</p>
</div><script src=“scripts/angular.js" >
</html>
![Page 14: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/14.jpg)
Directive usage
• Avoid<!-- directive: my-directive --><div class="my-directive"></div>
• Good<my-directive></my-directive><div my-directive></div>
![Page 15: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/15.jpg)
Directive build-in
ngApp
ngBind
ngBindHtmlngBindTemplate
ngBlurngChangengChecked
ngClass
ngClassEvenngClassOdd
ngClick
ngCloakngController
ngCopy
ngCsp
ngCut
ngDblclick
ngDisabledngFocus
ngFormngHidengHref
ngIf
ngIncludengInit
ngKeydown
ngKeypressngKeyup
ngList
ngModel
ngModelOptions
ngMousedown
ngMouseenterngMouseleave
ngMousemovengMouseoverngMouseup
ngNonBindable
ngOpenngPaste
ngPluralize
ngReadonlyngRepeat
ngSelected
ngShow
ngSrc
ngSrcset
ngStylengSubmit
ngSwitchngTranscludengValue
aform
input
input[checkbox]input[dateTimeLocal]
input[date]
input[email]
input[month]
input[number]
input[radio]input[text]
input[time]input[url]input[week]
script
selecttextarea
![Page 16: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/16.jpg)
Scope definition
Scope is an object that refers to the application model. It is an execution context for expressions.
![Page 17: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/17.jpg)
Scope hierarchical structure
Scopes are arranged in hierarchical structure which mimic the DOM structure of the application. Scopes can watch expressions and propagate events.
![Page 18: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/18.jpg)
Two-way data binding
![Page 19: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/19.jpg)
One-time binding
One-time expressions will stop recalculating once they are stable, which happens after the first digest if the expression result is a non-undefined value (v1.3+)
<p>Normal binding: {{name}}</p><p>One time binding: {{::name}}</p><ul>
<!-- items are bind once --><li ng-repeat="item in ::items">{{item.name}}</li>
</ul>
![Page 20: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/20.jpg)
Module definition
You can think of a module as a container for the different parts of your app – controllers, services, filters, directives, etc
![Page 21: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/21.jpg)
Module implementation
• Create a new modulevar myModule = angular.module(‘myModule’, [ ]);
• Get a modulevar myModule = angular.module(‘myModule’, [ ]);
• Add module dependenciesvar otherModule = angular.module(‘otherModule’, [‘ngRoute’, ‘myModule’]);
![Page 22: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/22.jpg)
Controller definition
In Angular, a Controller is a JavaScript constructor function that is used to augment the Scope
Do not use them to manipulate DOM.
![Page 23: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/23.jpg)
Controller sample
function MyController ($scope){
$scope.name = "Yoann";
$scope.doAction = function (name){console.log("Hello world "+name);
};}
angular.module('app').controller('MyCtrl', MyController);
<div ng-controller="MyCtrl"><input type="text" ng-model="name"><button ng-click="doAction(name)">Show in console</button>
</div>
![Page 24: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/24.jpg)
Controller
Talk is cheap
Show me the code
![Page 25: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/25.jpg)
Filter
A filter formats the value of an expression for display to the user. They can be used in view templates, controllers or services and it is easy to define your own filter.
![Page 26: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/26.jpg)
Filter usage
<span>{{ price | currency }}</span> <!-- $10.00 -->
<span>{{ now | date:'dd/MM/yyyy' }}</span> <!-- 01/10/2014 -->
<li ng-repeat="article in articles | limitTo:10"> ... </li> <!-- truncate the list to 10 articles -->
![Page 27: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/27.jpg)
Filter build in
currencydatefilterjsonlimitTolowercasenumberorderByuppercase
![Page 28: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/28.jpg)
Filter creation
function CheckmarkFilter (){return function(input) {
return input ? '\u2713' : '\u2718';};
}
angular.module('app').filter('checkmark', CheckmarkFilter);
\u2713 -> ✓\u2718 -> ✘
![Page 29: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/29.jpg)
Filter
Talk is cheap
Show me the code
![Page 30: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/30.jpg)
Service introduction
You can use services to organize and share code across your appAngular services are substitutable objects that are wired together using dependency injection (DI)
Angular services are lazily instantiated and singletons.
![Page 31: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/31.jpg)
Service build in
$anchorScroll$animate$cacheFactory$compile$controller$document$exceptionHandler$filter$http$httpBackend$interpolate$interval
$locale$location$log$parse$q$rootElement$rootScope$sce$sceDelegate$templateCache$templateRequest$timeout
$window$injector$provide$animate$aria$cookieStore$cookies$resource$route$routeParams$sanitize$swipe
![Page 32: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/32.jpg)
Dependency injection definition
Dependency Injection (DI) is a software design pattern that deals with how components get hold of their dependencies.
The Angular injector subsystem is in charge of • creating components• resolving their dependencies• providing them to other components as requested
![Page 33: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/33.jpg)
Dependency injection exemple
function MyController ($scope, $http, $log) {
$http.get('/api/articles').success(function (data){
$log.debug('Articles received');$scope.articles = data;
});}
angular.module('myModule').controller ('MyCtrl', MyController);
Injections
![Page 34: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/34.jpg)
Dependency injection minification issue
function a (b, c, d) {b.get('/api/articles').success(function(e){d.debug('Articles received');a.articles = e;});}angular.module('myModule').controller ('MyCtrl', a);
Unknown services : injections fail
![Page 35: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/35.jpg)
Dependency injection minification solutions
• Dependencies array
• $inject
• ng-annotate module
function MyController ($scope, $http, $log) { … }
angular.module('myModule').controller ('MyCtrl', [‘$scope’, ‘$http’, ‘$log’, MyController]);
function MyController ($scope, $http, $log) { … }
MyController.$inject = [‘$scope’, ‘$http’, ‘$log’];
angular.module('myModule').controller ('MyCtrl', MyController);
/* @ngInject */function MyController ($scope, $http, $log) { … }
angular.module('myModule').controller ('MyCtrl', MyController);
![Page 36: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/36.jpg)
Service and DI
Talk is cheap
Show me the code
![Page 37: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/37.jpg)
Service configuration block
Configuration blocks - get executed during the provider registrations and configuration phase. Only providers and constants can be injected into configuration blocks.
function MyConfig ($httpProvider, $logProvider){
$httpProvider.defaults.cache=false;$logProvider.debugEnabled(true);
}
angular.module(‘app’).config(MyConfig);
![Page 38: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/38.jpg)
Service run block
Run blocks - get executed after the injector is created and are used to kickstart the application. Only instances and constants can be injected into run blocks.
function MyRunBlock ($log){
$log.debug(‘app module is running’);}
angular.module(‘app’).run(MyRunBlock );
![Page 39: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/39.jpg)
Service creation methods
5 methods to create a AngularJS service :• Provider• Factory• Service• Value• Constant
![Page 40: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/40.jpg)
Service create with provider
function MyProvider (){
this.step = 24*60*60*1000; /* public. configurable */var length = 4; /* private. not configurable */
/* public. configurable */this.getLastDays = function (){
var now = Date.now();var step = this.step;var lastDays = [];
for(var i=1; i<length; i++){var date = new Date(now-i*step);lastDays.push(date);
}return lastDays;
};
/* create and return the service */this.$get = /* @ngInject */ function ($log){
var lastDays = this.getLastDays();$log.debug("last days computed !");return lastDays ;
};}angular.module('app').provider (' LastDays', MyProvider);
/* @ngInject */function MyConfig (LastDaysProvider){
LastDaysProvider.step = 2* LastDaysProvider.step;}angular.module('app').config (MyConfig);
/* @ngInject */function MyCtrl ($scope, LastDays){
$scope.lastDays = LastDays;}angular.module('app').controller(‘MyCtrl’, MyCtrl);
![Page 41: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/41.jpg)
Service create with factory
/* @ngInject */function MyCtrl ($scope, LastDays){
$scope.lastDays = LastDays;}angular.module('app').controller(‘MyCtrl’, MyCtrl);
/* @ngInject */function MyFactory ($log){
var length = 4;var step = 24*60*60*1000;var now = Date.now();
var lastDays = [];
for(var i=1; i<length; i++){var date = new Date(now-i*step);lastDays.push(date);
}
$log.debug("last days computed !");
return lastDays;}
angular.module('app').factory ('LastDays', MyFactory);
![Page 42: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/42.jpg)
Service create with service
/* @ngInject */function MyCtrl ($scope, LastDays){
$scope.lastDays = LastDays.data;}angular.module('app').controller(‘MyCtrl’, MyCtrl);
/* @ngInject */function MyService ($log){
var lastDays = this.getLastDays();$log.debug("last days computed !");this.data = lastDays;
}
MyService.prototype.getLastDays = function getLastDays (){
var length = 4;var step = 24*60*60*1000;var now = Date.now();var lastDays = [];
for(var i=1; i<length; i++){var date = new Date(now-i*step);lastDays.push(date);
}
return lastDays;};
angular.module('app').service ('LastDays', MyService);
![Page 43: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/43.jpg)
Constant & Value
• No dependency injection• Constant can be inject in config blocks
function LastDaysFunction (){
var length = 4;var step = 24*60*60*1000;var now = Date.now();
var lastDays = [];
for(var i=1; i<length; i++){var date = new Date(now-i*step);lastDays.push(date);
}return lastDays;
}
angular.module('app').constant('LastDaysAsConstant', LastDaysFunction);
angular.module('app').value('LastDaysAsValue', LastDaysFunction);
![Page 44: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/44.jpg)
Service creation summary
Method Configurable DI Service creation Provider name
module.provider() Yes YesBy calling the provider method$get
Service name+ 'Provider'
module.factory() No Yes By calling the provided method -
module.service() No YesBy creating a new instance of providedobject
-
module.value() No No Already exist -
module.constant() Yes No Already exist Service name
![Page 45: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/45.jpg)
Service
Talk is cheap
Show me the code
![Page 46: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/46.jpg)
The big AngularJS picture
![Page 47: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/47.jpg)
Routing definition
Routing allows you to organize the parts of your interface thanks to URL routes.
The routing functionnality is distributed separately from the core Angular framework.
![Page 48: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/48.jpg)
/* @ngInject */function RouteConfig ($routeProvider){
$routeProvider.when('/articles', {
templateUrl: 'partials/articles-list.html',controller: 'ArticlesListCtrl'
}).when('/articles/:articleId', {
templateUrl: 'partials/article-detail.html',controller: 'ArticleDetailCtrl',resolve : {
article : /* @ngInject */ function ($routeParams, Articles){return Articles.get({id : $routeParams.articleId});
} }
}).otherwise({
redirectTo: '/articles'});
}
angular.module('app').config(RouteConfig);
Routing configuration
URL routeTemplate nameController name
URL route with variable
Asynchronous data loader
![Page 49: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/49.jpg)
Routing api
• Configure a route$routeProvider.when (pathName, options)
• Redirect unknown routes$routeProvider.otherwise (redirectPathName)
• Get route variablesvar param = $routeParams.paramName
• Get current routevar current = $route.current
• Change route programmatically$location.path(path)
• Observe route events$rootScope.$on(event, cb) Events : $routeChangeStart, $routeChangeSuccess, $routeChangeError, $routeUpdate
![Page 50: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/50.jpg)
Routing ui-router
AngularUI Router is a routing framework, which allows you to organize the parts of your interface into a state machinehttp://angular-ui.github.io/ui-router/
Allow nested and multiple views
![Page 51: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/51.jpg)
Routing
Talk is cheap
Show me the code
![Page 52: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/52.jpg)
Form validation 1/3
<form name=“userForm" ng-submit="update(user)" >Name:<input type="text" ng-model="user.name" name="uName" required /><br />
E-mail:<input type="email" ng-model="user.email" name="uEmail" required/><br />
<input type="checkbox" ng-model="user.agree" name="uAgree" required />I agree <br />
<button type="submit">SAVE</button></form>
![Page 53: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/53.jpg)
Form validation 2/3
userForm scope variable is a booleans map :• $valid• $invalid• uEmail
• $valid• $invalid• $dirty• $pristine• $touched (v1.3+)• $untouched (v1.3+)• $error
• required• email
• uName• $valid• $invalid• …
![Page 54: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/54.jpg)
Form validation 3/3
<form name="userForm" ng-submit="update(user)" novalidate>Name:<input type="text" ng-model="user.name" name="uName" required /><br /><div class="error" ng-show="userForm.uName.$dirty && userForm.uName.$invalid">Name invalid</div>
E-mail:<input type="email" ng-model="user.email" name="uEmail" required/><br /><div class="error" ng-show="userForm.uEmail.$dirty && userForm.uEmail.$error.required">Required email</div><div class="error" ng-show="userForm.uEmail.$dirty && userForm.uEmail.$error.email">Email invalid</div>
<input type="checkbox" ng-model="user.agree" name="userAgree" required /> I agree <br /><div class="error" ng-show="userForm.userAgree.$dirty && userForm.userAgree.$error.required">Be agree</div>
<button type="submit" ng-disabled="userForm.$invalid">SAVE</button></form>
![Page 55: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/55.jpg)
Form validation styling
To allow styling of form as well as controls, ngModel adds these CSS classes:• ng-valid: the model is valid• ng-invalid: the model is invalid• ng-valid-[key]: for each valid key added by $setValidity• ng-invalid-[key]: for each invalid key added by $setValidity• ng-pristine: the control hasn't been interacted with yet• ng-dirty: the control has been interacted with• ng-touched: the control has been blurred• ng-untouched: the control hasn't been blurred
input.ng-invalid.ng-dirty {background-color: #FF0000;
}
![Page 56: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/56.jpg)
Form validation
Talk is cheap
Show me the code
![Page 57: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/57.jpg)
Create directive
To be continued…
![Page 58: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/58.jpg)
To be continuted…
• Directive creation• Publish/subscribe with $scope• Animation• ngMessages• Best practice
• https://github.com/toddmotto/angularjs-styleguide• https://github.com/johnpapa/angularjs-styleguide
• Error management• IE Compatibilty• …
![Page 59: Introduction to AngularJS](https://reader033.fdocuments.us/reader033/viewer/2022052508/5596d8041a28aba4098b4728/html5/thumbnails/59.jpg)
Questions?