SlideShare a Scribd company logo
1 of 31
Angular
Jan Ranostaj
Angular Module
• Modul ako container
• Definovanie Angular Module
• Logická organizácia kódu
• Setter & Getter
• Best practice
• Angular modul predstavuje kolekciu
directives, controllers, factories, services....
• Samostatne nezávislý modul
Definovanie Modulu
var myModule = angular.module('myModule', []);
Logická organizácia
Spájanie modulov podľa funkcionality
nie podľa typu
Inbox
Email App
Folder Tags
Compose
Editor Address Book
Rozdelenie modulov EmailApp
angular.module("Editor.directives", []); // Editor Directives
angular.module("Editor.controllers", []); // Editor Controllers
angular.module("Editor", ["Editor.controllers","Editor.directives"]); //
Editor Module
angular.module("Folder", []);// Folder Module
angular.module("Tags", []);// Tags Module
angular.module("AdressBook", []); // AdressBook Module
angular.module("Inbox", ["Folder", "Tags"]); // Inbox Module
angular.module("Compose", ["Editor", "AdressBook"]); // Compose Module
angular.module("EmailApp", ["Inbox", "Compose"]); // EmailApp Module
Setter & Getter
Setter – definuje modul
Getter – vracia modul
var myModule = angular.module('myModule', []);
angular.module('myModule').controller(…);
Best practice
Setter – definicia modulu v
app
Getter – pre controller
(function (app) {
app.controller("MainCtrl", MainCtrl);
// Controller Constructor
function MainCtrl() {}
})(angular.module('app.controllers'));
(function () {
angular.module('app', []);
})();
Factories & Services
• Factory vs Service
• Provider
• Kedy použiť Factory?
• Kedy použiť Service?
Factories vs Services
Factory – Objekt s funkciami
Service - konštruktor “new”
function service(name, constructor) {
return factory(name, ['$injector', function ($injector) {
return $injector.instantiate(constructor);
}]);}
function factory(name, factoryFn, enforce) {
return provider(name, {
$get: enforce !== false ? enforceReturnValue(name, factoryFn) :
factoryFn
});
}
Provider
Factory s možnosťou configurácie
var app = angular.module("app",[]);
app.provider("email", function () {
var type;
return {
setType: function (value) { // funkcia sa vola pri configuracii
type = value;
},
$get: function () { // get Metoda ktoru vola angular ked injektuje provider
return {
title: type + " Email"
};
}
};
});
Provider - Konfigurácia
Config
Controller:
app.config(function (emailProvider) {
emailProvider.setType("Archived");
});
app.controller("AppCtrl", function ($scope, email) {
$scope.title = email.title; // Archived Email
}});
Kedy použiť Factory?
• Keď potrebujeme väčšiu komplexnosť
• Keď potrebujeme zabezpečiť konfiguráciu
(function(app){
app.factory("myFactory", myFactory);
function myFactory() {
var factory = {
foo:foo
}
return factory;
//////////
function foo() {}
})(angular.module('app'));
Kedy použiť Service?
• Vznikne inštancia konštruktora
• Potrebujeme dostať do controllera inštanciu tiredy
• ES6 syntax
class MyService {
sayHello() {
console.log('hello');
}
}
app.service('MyService',
MyService);
(function(app){
app.service("myService",
myService);
function myService() {
this.foo = function() {}
}
})(angular.module('app'));
Directives
• Samostatné nezávislé funkčné elementy
• Manipulácia s DOM
• Znovu použitelný kód (DRY princíp)
• Nezávislé $scope
• Build-in directives ng-bind, ng-model, ng-if…
• Vlastné HTML elementy (components)
Directives - Scope
Scope Property @
Pristup k hodnote ako string
http://jsbin.com/xegebu/edit?html,js,output
<my-directive name=“{{name}}"></my-directive>
angular.module('app').directive('myDirective',
function () {
return {
scope: {
name: '@' // string value
},
template: 'Name: {{ name }}'
};
}).controller("ctrl", function($scope){
$scope.name = "Jano";
});
Scope Property =
Pristup k hodnote two-way binding
http://jsbin.com/guquke/edit?html,js,output
<my-directive name="name"></my-directive>
angular.module('app').directive('myDirective',
function () {
return {
scope: {
name: '=' // Two-way binding
},
template: 'Name: {{ name }}'
};
}).controller("ctrl", function($scope){
$scope.name = "Jano";
});
Scope Property &
Pristup k funkcii
<my-directive action=“loadData()"></my-directive>
angular.module('app').directive('myDirective', function () {
return {
scope: {
action: '&'
},
template: 'Name: {{ name }}'
};
}).controller("ctrl", function($scope){
var counter = 0;
$scope.loadData = function() {
counter++;
}
});
Scope Property &
Predávania parametrov funkcii
http://jsbin.com/bemaca/edit?html,js,console,output
<my-directive action=“loadData"></my-directive>
angular.module('app', []).directive('myDirective', function() {
return {
scope: {
action: '&'
},
restrict: 'EA',
template: '<button ng-click="sendParam()">Add</button>',
link: function(scope, elem, attr) {
scope.sendParam = function() {
scope.action()("Param");
}
}
};
}).controller("ctrl", function($scope) {
$scope.loadData = function(param) {
alert(param)
}
});
Komunikácia medzi direktívami
• 2 directives, ten istý element http://jsbin.com/dadewu/edit?html,js,console
– Require Controller: [“car”]
– Events $broadcast, $emit
• Parent, child directives - http://jsbin.com/zubufu/edit?html,js,console
– Require Controller: [“^car”]
– Events $broadcast, $emit
• Susedné (sibling directive) http://jsbin.com/zavonu/edit?html,js,console
– Events $broadcast, $on
<div car engine></div>
<div car >
<div engine></div>
</div>
<div car ></div>
<div engine ></div>
Compile, Pre, a Post funkcie
Compile function
– Ak chceme vykonať zmeny v DOM (template) ešte
predtým ako angular vytvorí inštanciu elementu a scope
var app = angular.module('app', []);
app.directive('myDirective', myDirective);
function myDirective(){
return function(){
return {
restrict: 'E',
compile: function(tElem, tAttrs){
}
}
}
}
Compile, Pre, a Post funkcie
Pre-Link function
– Ak chceme vykonať nejakú logiku kódu potom ako Angular
skompiloval všetky child elementy ale ešte predtým ako je
scope spojený s templatom
var app = angular.module('app', []);
app.directive('myDirective', myDirective);
function myDirective(){
return function(){
return {
restrict: 'E',
compile: function(tElem, tAttrs){
return {
pre: function(scope,element,attr,controller){}
}
}
}
}
}
Compile, Pre, a Post funkcie
Post-Link function
– Posledná funkcia ktorá sa vykoná. Template je spojený so
scope a view može vykonať two-way binding.
– Môžete vykonať všetky zmeny s DOM, vytvárať eventy atď.
var app = angular.module('app', []);
app.directive('myDirective', myDirective);
function myDirective(){
return function(){
return {
restrict: 'E',
compile: function(tElem, tAttrs){
return {
post: function(scope,element,attr,controller){}
}
}
}
}
}
Controllers
Ako ich správne použiť
•Spájanie $scope a view
•Definovanie správanie $scope
objektu
•Logika potrebná pre view
Ako ich nepoužívať
•Akékoľvek manipulácie s
DOM
•Zdielanie dát medzi
controllermi
•Filtrovanie výstupu
Controller AS syntax
• $scope => this
• Controller => Class
• prototype inheritnece
Controller AS syntax
(function(app){
app.controller("MyCtrl", MyCtrl);
function MyCtrl(){
this.name = null;
};
angualar.extend(MyCtrl.prototype,{
init: function(){
this.name = 'Jano';
}
})
})(angular.module('app'));
<!-- In Your Binding -->
<div ng-controller="MyCtrl as ctrl">
<span></span>
</div>
Summary
• Spájanie modulov podľa funkcionality nie podľa typu
• Rozdeľovat aplikáciu na menšie nezávislé moduly
• Používať Factory, v prípade že potrebujeme konfiguráciu tak
Provider
• Na manipuláciu s DOM používať Direcives
• Používať Directives všade kde sa dá vytvoriť samostatne
funkčný celok
• Používať controller AS syntax Controller = Class
Resources
• AngularJS Hub - vzdelávanie, príklady
– http://www.angularjshub.com/
• Ng-newsletter – príklady, články
– http://www.ng-newsletter.com/
• Thinkster - vzdelávanie
– https://thinkster.io/
• Ng-nuggets – code snippets
– http://ng.malsup.com/
• Recipes with Angular.js – krátke návody, vysvetlenia
– http://fdietz.github.io/recipes-with-angular-js/
Happy coding 

More Related Content

Featured

How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
ThinkNow
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
Kurio // The Social Media Age(ncy)
 

Featured (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Angular tips

  • 2. Angular Module • Modul ako container • Definovanie Angular Module • Logická organizácia kódu • Setter & Getter • Best practice
  • 3.
  • 4. • Angular modul predstavuje kolekciu directives, controllers, factories, services.... • Samostatne nezávislý modul Definovanie Modulu var myModule = angular.module('myModule', []);
  • 6. Spájanie modulov podľa funkcionality nie podľa typu Inbox Email App Folder Tags Compose Editor Address Book
  • 7. Rozdelenie modulov EmailApp angular.module("Editor.directives", []); // Editor Directives angular.module("Editor.controllers", []); // Editor Controllers angular.module("Editor", ["Editor.controllers","Editor.directives"]); // Editor Module angular.module("Folder", []);// Folder Module angular.module("Tags", []);// Tags Module angular.module("AdressBook", []); // AdressBook Module angular.module("Inbox", ["Folder", "Tags"]); // Inbox Module angular.module("Compose", ["Editor", "AdressBook"]); // Compose Module angular.module("EmailApp", ["Inbox", "Compose"]); // EmailApp Module
  • 8. Setter & Getter Setter – definuje modul Getter – vracia modul var myModule = angular.module('myModule', []); angular.module('myModule').controller(…);
  • 9. Best practice Setter – definicia modulu v app Getter – pre controller (function (app) { app.controller("MainCtrl", MainCtrl); // Controller Constructor function MainCtrl() {} })(angular.module('app.controllers')); (function () { angular.module('app', []); })();
  • 10. Factories & Services • Factory vs Service • Provider • Kedy použiť Factory? • Kedy použiť Service?
  • 11. Factories vs Services Factory – Objekt s funkciami Service - konštruktor “new” function service(name, constructor) { return factory(name, ['$injector', function ($injector) { return $injector.instantiate(constructor); }]);} function factory(name, factoryFn, enforce) { return provider(name, { $get: enforce !== false ? enforceReturnValue(name, factoryFn) : factoryFn }); }
  • 12. Provider Factory s možnosťou configurácie var app = angular.module("app",[]); app.provider("email", function () { var type; return { setType: function (value) { // funkcia sa vola pri configuracii type = value; }, $get: function () { // get Metoda ktoru vola angular ked injektuje provider return { title: type + " Email" }; } }; });
  • 13. Provider - Konfigurácia Config Controller: app.config(function (emailProvider) { emailProvider.setType("Archived"); }); app.controller("AppCtrl", function ($scope, email) { $scope.title = email.title; // Archived Email }});
  • 14. Kedy použiť Factory? • Keď potrebujeme väčšiu komplexnosť • Keď potrebujeme zabezpečiť konfiguráciu (function(app){ app.factory("myFactory", myFactory); function myFactory() { var factory = { foo:foo } return factory; ////////// function foo() {} })(angular.module('app'));
  • 15. Kedy použiť Service? • Vznikne inštancia konštruktora • Potrebujeme dostať do controllera inštanciu tiredy • ES6 syntax class MyService { sayHello() { console.log('hello'); } } app.service('MyService', MyService); (function(app){ app.service("myService", myService); function myService() { this.foo = function() {} } })(angular.module('app'));
  • 16. Directives • Samostatné nezávislé funkčné elementy • Manipulácia s DOM • Znovu použitelný kód (DRY princíp) • Nezávislé $scope • Build-in directives ng-bind, ng-model, ng-if… • Vlastné HTML elementy (components)
  • 18. Scope Property @ Pristup k hodnote ako string http://jsbin.com/xegebu/edit?html,js,output <my-directive name=“{{name}}"></my-directive> angular.module('app').directive('myDirective', function () { return { scope: { name: '@' // string value }, template: 'Name: {{ name }}' }; }).controller("ctrl", function($scope){ $scope.name = "Jano"; });
  • 19. Scope Property = Pristup k hodnote two-way binding http://jsbin.com/guquke/edit?html,js,output <my-directive name="name"></my-directive> angular.module('app').directive('myDirective', function () { return { scope: { name: '=' // Two-way binding }, template: 'Name: {{ name }}' }; }).controller("ctrl", function($scope){ $scope.name = "Jano"; });
  • 20. Scope Property & Pristup k funkcii <my-directive action=“loadData()"></my-directive> angular.module('app').directive('myDirective', function () { return { scope: { action: '&' }, template: 'Name: {{ name }}' }; }).controller("ctrl", function($scope){ var counter = 0; $scope.loadData = function() { counter++; } });
  • 21. Scope Property & Predávania parametrov funkcii http://jsbin.com/bemaca/edit?html,js,console,output <my-directive action=“loadData"></my-directive> angular.module('app', []).directive('myDirective', function() { return { scope: { action: '&' }, restrict: 'EA', template: '<button ng-click="sendParam()">Add</button>', link: function(scope, elem, attr) { scope.sendParam = function() { scope.action()("Param"); } } }; }).controller("ctrl", function($scope) { $scope.loadData = function(param) { alert(param) } });
  • 22. Komunikácia medzi direktívami • 2 directives, ten istý element http://jsbin.com/dadewu/edit?html,js,console – Require Controller: [“car”] – Events $broadcast, $emit • Parent, child directives - http://jsbin.com/zubufu/edit?html,js,console – Require Controller: [“^car”] – Events $broadcast, $emit • Susedné (sibling directive) http://jsbin.com/zavonu/edit?html,js,console – Events $broadcast, $on <div car engine></div> <div car > <div engine></div> </div> <div car ></div> <div engine ></div>
  • 23. Compile, Pre, a Post funkcie Compile function – Ak chceme vykonať zmeny v DOM (template) ešte predtým ako angular vytvorí inštanciu elementu a scope var app = angular.module('app', []); app.directive('myDirective', myDirective); function myDirective(){ return function(){ return { restrict: 'E', compile: function(tElem, tAttrs){ } } } }
  • 24. Compile, Pre, a Post funkcie Pre-Link function – Ak chceme vykonať nejakú logiku kódu potom ako Angular skompiloval všetky child elementy ale ešte predtým ako je scope spojený s templatom var app = angular.module('app', []); app.directive('myDirective', myDirective); function myDirective(){ return function(){ return { restrict: 'E', compile: function(tElem, tAttrs){ return { pre: function(scope,element,attr,controller){} } } } } }
  • 25. Compile, Pre, a Post funkcie Post-Link function – Posledná funkcia ktorá sa vykoná. Template je spojený so scope a view može vykonať two-way binding. – Môžete vykonať všetky zmeny s DOM, vytvárať eventy atď. var app = angular.module('app', []); app.directive('myDirective', myDirective); function myDirective(){ return function(){ return { restrict: 'E', compile: function(tElem, tAttrs){ return { post: function(scope,element,attr,controller){} } } } } }
  • 26. Controllers Ako ich správne použiť •Spájanie $scope a view •Definovanie správanie $scope objektu •Logika potrebná pre view Ako ich nepoužívať •Akékoľvek manipulácie s DOM •Zdielanie dát medzi controllermi •Filtrovanie výstupu
  • 27. Controller AS syntax • $scope => this • Controller => Class • prototype inheritnece
  • 28. Controller AS syntax (function(app){ app.controller("MyCtrl", MyCtrl); function MyCtrl(){ this.name = null; }; angualar.extend(MyCtrl.prototype,{ init: function(){ this.name = 'Jano'; } }) })(angular.module('app')); <!-- In Your Binding --> <div ng-controller="MyCtrl as ctrl"> <span></span> </div>
  • 29. Summary • Spájanie modulov podľa funkcionality nie podľa typu • Rozdeľovat aplikáciu na menšie nezávislé moduly • Používať Factory, v prípade že potrebujeme konfiguráciu tak Provider • Na manipuláciu s DOM používať Direcives • Používať Directives všade kde sa dá vytvoriť samostatne funkčný celok • Používať controller AS syntax Controller = Class
  • 30. Resources • AngularJS Hub - vzdelávanie, príklady – http://www.angularjshub.com/ • Ng-newsletter – príklady, články – http://www.ng-newsletter.com/ • Thinkster - vzdelávanie – https://thinkster.io/ • Ng-nuggets – code snippets – http://ng.malsup.com/ • Recipes with Angular.js – krátke návody, vysvetlenia – http://fdietz.github.io/recipes-with-angular-js/