Basics of AngularJS

34
BASICS OF ANGULARJS

Transcript of Basics of AngularJS

Page 1: Basics of AngularJS

BASICS OF ANGULARJS

Page 2: Basics of AngularJS

TOPICS Definition Key features Demo examples Exercises

Page 3: Basics of AngularJS

DEFINITION• Web application framework• Default MVC framework… but not required• JavaScript library• Open source• Maintained by Google• Used for single page application (SPA)• Provide templating mechanism• Has the largest user base• Easy to test• . . .

Page 4: Basics of AngularJS

KEY FEATURES2-WAY DATA

BINDINGDEPENCENC

Y INJECTION

TEMPLATING

EXPRESSIONS

MVC DIRECTIVES

FILTERS SERVICES

TESTING

MODULARITY

SCOPING

ANIMATIONS

FACTORIES PROVIDERS

ROUTING VALIDATION

CONTROLLERS

CONSTANTS

Page 5: Basics of AngularJS

KEY FEATURES2-WAY DATA

BINDINGDEPENCENC

Y INJECTION

TEMPLATING

EXPRESSIONS

MVC DIRECTIVES

FILTERS SERVICES

TESTING

MODULARITY

SCOPING

ANIMATIONS

FACTORIES PROVIDERS

ROUTING VALIDATION

CONTROLLERS

CONSTANTS

Page 6: Basics of AngularJS

MVC

Stores data retrieved from the controller logic and shown on the viewmodel

controllerview Display the model data to the user

Manipulate with the model data or the associate representation of the data on the view

View

Model

ControllerUpdate UI

Update model

Model changed

User action

Model changed

Page 7: Basics of AngularJS

2-WAY DATA BINDING|

E-mail address:

var email = ῾῾;

watcher

watcher

Binds the value of the model to the view and does not have additional way to determine if the value in the view has been changed by the user1-way

2-way Binds the value of the model to the view while also bind the input on the view with the model, so when the input is changed the value of the model is changed as well

Page 8: Basics of AngularJS

DEPENDENCY INJECTION (DI)

• Increase modularity• Makes the program extensible• Separation of concerns• Single responsibility• Components easy to test and maintain

Dependency Injection is a software design pattern in which components are given their dependencies instead of hard coding them within the component. 

definition

usage

Page 9: Basics of AngularJS

TECHNOLOGY STACK

Page 10: Basics of AngularJS

HOW TO START?• Angular is designed for SPA. We are going to have one main HTML file that

includes all info that is necessary so that Angular can function normally.

• Angular is nothing more but an JavaScript library. Download it and include it in your HTML!

LINK: https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js

• Download it as NPM dependency:

npm install --save angular

Page 11: Basics of AngularJS

HOW TO START?• The Angular application starts from the DOM element where the ng-app is declared• ng-app holds the name of the Angular application

<div ng-app="myApp"></div>• Declare the name of the application in separate JS file and include it in the main

HTML fileconst app = angular.module('myApp', []);

Page 12: Basics of AngularJS

CONTROLLER• Controls the data flow• Create controller on given module:

app.controller('myCtrl', () => {. . .

});• Tell the application where you want this controller to be in action on the HTML:

<div ng-controller="myCtrl"></div>• Make sure that the ng-controller is nested inside the DOM element where ng-

app attribute is attached!• The controller is a constructor function which is initialized when Angular

discovers the ng-controller directive.

Page 13: Basics of AngularJS

$SCOPE• For the controller instance a child scope object is created and injected as a

dependency of the constructor function.• Every function and model that is defined in the controller and applied on the

view must be augmented to the $scope object.

app.controller('myCtrl', ($scope) => {

$scope.company = 'Endava'; });

Dependency

Injection

Page 14: Basics of AngularJS

$ROOTSCOPE• For each Angular application there is only one root scope: $rootScope which

contains all children scopes. • Child scope - $scope is the scope of the controller.• On controller scope can be a parent of another scope if the second

controller is nested in the first one.• Scoping forms tree hierarchy in the application

• Every time a expression is added in the HTML it is the $scope of the controller which is searched first. If the expression is not found, the parent scope is searched.

Page 15: Basics of AngularJS

$ROOTSCOPE<body ng-app='app‘>

{{someValue}}

<div ng-controller='ctrl1'>

</div><div ng-controller='ctrl2'>

</div><div ng-controller='ctrl3'>

{{someValue}}</div>

</body>

$rootScope

$scope

$scope

$scope

someValue

Page 16: Basics of AngularJS

EXPRESSIONS• Data binding on HTML is done with expressions• They are much like JavaScript expressions (except they forbid function

declaration as expression)• They are evaluated against the $scope object• Style of writing expressions:• Using ng-bind: <span ng-bind='email'></span>• Using double curly notation: <span> {{email}} </span>

Examples:• <span>{{ 2 + 5 }}</span>• <p>{{ user.email }}</p>• <button ng-click='saveUser()'>SAVE</button>

Page 17: Basics of AngularJS

EXPRESSIONSapp.controller('myCtrl', ($scope) => {

$scope.company = 'Endava'; });

<div ng-app=‘myApp‘><div ng-controller=‘myCtrl‘>

Company name: {{ company }}</div>

</div>

JavaScript

HTML

Page 18: Basics of AngularJS

SERVICE• Function or object used to organize and share code across the application• The service is wired to the controller using DI• Every service is wrapped to an provider and like that is available everywhere in

the application• It is lazy instantiated – only when it is needed• It is singleton – is instantiated only once• They are invoked as a constructor with the new keyword

app.service('myService', class {

getName() { . . . }getEmail() { . . . }

});

Page 19: Basics of AngularJS

FACTORY• Similar to services• They are invoked as functions, not as constructor functions• Can be wired to the controller using DI• The controller will have the value returned from the invocation of the function

instance which is the second argument of factory() method.

app.factory('myService', () =>({

getName: function() { . . . },

getEmail: function() { . . . }}));

Page 20: Basics of AngularJS

FACTORYapp.factory('myService', () => ({

getName: function() { return 'Endava' } }));

app.controller(‘myCtrl‘, ($scope, myService) => {$scope.company = myService.getName();

});

Page 21: Basics of AngularJS

BUILD-IN SERVICES• There are 30 build-in services in Angular• $http used for HTTP request• $location makes the URL available in the application• $window window object wrapper• $animate used for animations• $filter contains default filters• $httpBackend used for HTTP requests in testing• $locale used for localization • $parse used for parsing content• $q used for resolving/rejecting promises• $timeout timeout wrapper• . . . etc

Page 22: Basics of AngularJS

$HTTP• $http is a build-in service for asynchronous HTTP requests• All HTTP methods of $http return promise object which:• resolved successfully – code 200• rejected – code 4XX, 5XX

• General usage:$http({

method:'post',url:'/api/users',data: userObject

}).then((response) => {// success

}, (error) => {// error

});

$http({

method:'get',url:'/api/user‘,params: {

userId: 1}

}).then((response) => {// success

}, (error) => {// error

});

Page 23: Basics of AngularJS

DIRECTIVE• Angular allows us to extend HTML with new attributes called directives• Build-in directives:• ng-app initialize Angular application• ng-controller initialize controller• ng-init create init values that are used in the

controller• ng-bind bind expression on HTML (1-way data

binding)• ng-model allow 2-way data binding. Used on input

elements• ng-repeat used for iterations• ng-options used for iterative population of options in

select element• ng-if will show the element to which it is attached if

the condition is satisfied• ng-disabled if true disables the DOM element• ng-selected if true for checkbox, the checkbox will be checked• ng-readonly makes a text field read only• ng-href allow Angular variable to be binded to

the href attribute• . . . etc

Page 24: Basics of AngularJS

DIRECTIVEExamples:$scope.cities = [

{name: 'Skopje', country: 'MKD'},{name: 'Washington', country: 'US'},{name: 'Moscow', country: 'RU'},

];

<tr ng-repeat=“city in cities track by $index”><td>{{city.name}}</td><td>{{city.country}}</td>

</tr>

<option ng-options=“city.name for city in cities track by $index”></option>

Page 25: Basics of AngularJS

CUSTOM DIRECTIVE• Custom directive can be:• Element <endava-title></end-user-list>• Attribute <div endava-user-list></div>• Class name <div class='endava-user-list'></div>• Comment <!-- directive: endava-user-list -->

• Directive are always declared with camel-case but used with kebab-case

Example:app.directive('endavaTitle', () => ({

restrict: 'E',template: ''<h1>E N D A V

A</h1>''}));

<endava-title></endava-title>

Used as:

Page 26: Basics of AngularJS

CUSTOM DIRECTIVE• Restriction:• Element E• Attribute A• Comment M• Class C

• By default the restrict value is EA which means that the directive can be used as element or attribute

• template vs. templateUrl propertyapp.directive('endavaTitle', () => ({

restrict: 'E',templateUrl:

‘/pages/index.html'}));

Page 27: Basics of AngularJS

CUSTOM DIRECTIVE• Scope of directive• Can use the scope of the controller• Can have isolated scope:

app.directive('endavaTitle', function() {

return {restrict: 'A',templateUrl:

'/pages/title.html',scope: {

title: ‘@companyName'

}}

});

<h1>{{title}}</h1>

<div><endava-title company-

name='ENDAVA‘></endava-title>

</div>

/pages/title.html

/index.html

@ string binding

= 2-way data binding& method reference

Page 28: Basics of AngularJS

DIGEST CYCLE, DIRTY CHECKING AND WATCHERS

ModelDirty

checking

watcher

watcher

watcher

{{E}}

ng-model

ng-bind

Dirty checking VIEW

EVENT

Page 29: Basics of AngularJS

TIME FOR PRACTICE

Page 30: Basics of AngularJS

EXERCISES1.Create an Angular application that will display the top

20 movies that are now playing in theaters around the world!

2.Extend the previous application with an option to see list of actors and actresses for each movie!

3.Extend the list of movies so that the user can load more movies from the same list of movies that are now playing!

Page 31: Basics of AngularJS

EXERCISESUse the APIs provided by themoviedb.orgAPI endpoints:• Movies that are now playing:

https://api.themoviedb.org/3/movie/now_playing?api_key={api_key}https://api.themoviedb.org/3/movie/now_playing?api_key={api_key}&page={page_number}

•List of actors and actresses for a given movie:https://api.themoviedb.org/3/movie/{movie_id}/credits?api_key={api_key}

• Images endpoint: https://image.tmdb.org/t/p/w185/{img_path}

api_key=6e44c855f8bb700398820bc37a01ff6c For more info: https://developers.themoviedb.org/3/getting-started

Page 32: Basics of AngularJS

EXTRA EXERCISES4.Create directive for rating movies!

5.Extend the application so that the user should be able to filter movies by genre type. The API endpoint for genres:

https://api.themoviedb.org/3/genre/movie/list?api_key={api_key}

Page 33: Basics of AngularJS

QUESTIONS?

Page 34: Basics of AngularJS

THANK YOU! Filip Janevski Skype: en_fjanevski

Mail: [email protected]

Presentation http://www.slideshare.net/FilipJanevski1/basics-of-angularjs