SlideShare a Scribd company logo
ยฉ Copyright SELA software & Education Labs Ltd. | 14-18 Baruch Hirsch St Bnei Brak, 51202 Israel | www.selagroup.com
SELA DEVELOPER PRACTICE
MAY 31, 2015 โ€“ JUNE 4, 2015
Sebastian Pederiva
Tips for Angular Applications
Senior Consultant
sebastianp@sela.co.il
@spederiva
tiny.cc/SebastianBlog
Starting
Project Structure
Roll your own
Angular Seed
https://github.com/angular/angular- seed
Project Structureโ€ฆby components
Add Suffix to the file names
Easy to read and understand
Essential for โ€œcomponent typeโ€ structure
Help make better automation and testing
product-list.ctrl.js
product-list.tpl.html
product-list.fltr.js
product-list.fctry.js
product-list.srv.js
product-list.const.js
product-list.val.js
Separate to Modules
var corelist = app.module("app.core.list", []);
corelist.controller("app.core.list.listCtrl", ...)
angular.module(โ€œapp.common.services")
.service("myApp.common.services.product"
Golden Rules
Controllers should never refer to any DOM
elements
Controllers should call services vs. holding too
much business logic
Avoid $rootScope, try to use services instead
Expression {{}} vs ng-cloak
Minimizing Angular Files
Minimizing process will replace variable names
compromising the dependency injection
someModule.controller('MyController', ['$scope', function($scope) {
$scope.name = "Sebastian";
}]);
someModule.controller('MyController', function ($scope) {
$scope.name = "Sebastian";
});
someModule.controller('MyController', function (a) {
a.name = "Sebastian";
});
One Time Binding
Use double colon ::
https://code.angularjs.org/1.3.15/docs/guide/e
xpression#one-time-binding
For previous versions:
https://github.com/Pasvaz/bindonce
<p id="one-time-binding-example">
One time binding: {{::name}}
</p>
Controller Inheritance
app.controller("ChildCtrl", ["$scope", function ($scope) {
$scope.childText = "childText"
$scope.text = "childTextโ€
}]);
app.controller("ParentCtrl", ["$scope", function ($scope) {
$scope.parentText = "parentText"
$scope.text = "parentTextโ€
}]);
<div ng-controller="ParentCtrlโ€>
<div ng-controller="ChildCtrlโ€>
{{parentText}}
<br/>
{{childText}}
<br/>
{{text}}
</div>
</div>
Controller Inheritance
app.controller("ChildCtrl", function ($scope, $controller) {
$controller("ParentCtrl", {$scope: $scope});
$scope.childText = "childText";
$scope.text = "childText";
});
app.controller("ParentCtrl", ["$scope", function ($scope) {
$scope.parentText = "parentText"
$scope.text = "parentTextโ€
}]);
<div ng-controller="ChildCtrlโ€>
{{parentText}}
<br/>
{{childText}}
<br/>
{{text}}
</div>
Avoid Watchers
$watch occurs when the users clicks on an item,
not when the model changes
Consider using events instead
Minimize use watchers
Angular uses dirty checking to keep track of all
the changes in app
$watch() vs. $watchCollection()
$watch has 3 parameters
Use $watchCollection, it only checks the first
layer of objectโ€™s properties
http://www.bennadel.com/blog/2566-scope-
watch-vs-watchcollection-in-angularjs.htm
http://plnkr.co/edit/Pbvo6AqME081rZ2RVKDU?
p=preview
ng-repeat, track when possible
ngRepeat does not allow duplicate items in
arrays
Track by to increase performance
Default tracking
<div ng-repeat=โ€item in collection track by $id(obj)โ€>
Own tracking
<div ng-repeat=โ€item in collection track by item.idโ€>
https://docs.angularjs.org/api/ng/directive/ngR
epeat#tracking-and-duplicates
ng-repeat
How many times will getPrice function be
called?
Use watch collection to calculate everything
when the controller is first invoked
<tr ng-repeat="item in items">
<td>{{item.name}}</td>
<td>{{item.description}}</td>
<td>{{getPrice(item.id)}}</td>
</tr>
ng-repeat cont
<tr ng-repeat="item in items">
<td>{{item.name}}</td>
<td>{{item.description}}</td>
<td>{{item.price}}</td>
</tr>
$scope.$watchCollection('items', function (newItems) {
for (var i = 0; i < newItems.length; i++) {
newItems[i].price = getPrice(newItems.id);
}
$scope.items = newItems;
});
Avoid ng-repeat for infinite scroll
Memory Leaks
Performance problem
Possible solution:
http://www.williambrownstreet.net/blog/2013/0
7/angularjs-my-solution-to-the-ng-repeat-
performance-problem
Debounce ng-model
Lot of updates?
https://docs.angularjs.org/api/ng/directive/ng
ModelOptions
<input
ng-model="nameโ€
ng-model-options="{ debounce: 500 }โ€ />
Use ng-if instead of ng-show
ng-show will render an element, and use
display:none to hide it
ng-if will actually removes the element from
DOM, and will re-create it, if itโ€™s needed.
Promise you use Promises
Prefer Promises Over Callbacks
Follow The โ€˜...ingโ€™ Convention
Clear Indication Youโ€™re getting a Promise
function gettingUsers(){
return $http()...
}
gettingUsers()
.success()
.error()
Destroying Memory Leaks
Use $scope.$on('$destroy', โ€ฆ)
Remove handlers
Clean up resources which wonโ€™t be garbage
collected automatically
module.controller("TestController", function ($scope, $timeout) {
var onTimeout = function () {
$scope.value += 1;
timer = $timeout(onTimeout, 1000);
};
var timer = $timeout(onTimeout, 1000);
$scope.value = 0;
$scope.$on("$destroy", function () {
if (timer) {
$timeout.cancel(timer);
}
});
});
Managing the Timeโ€ฆuse moment.js
https://github.com/urish/angular-moment
<span am-time-ago="message.time">
</span>
Use Batarang
Debugging
Pause On Caught Exceptions
Debugging
Attach DOM Breakpoints
Logging
Avoid using console.log in your controllers
Use $log instead
$log can be extended to provide additional
logging capabilities
Forget jQuery Exists
jQuery
-- Use angular.element instead of $() selector --
Search for a jQuery-equivalent instead
ยป Examples
-- html(), text(), val()
ยป Ask whether you can use directives instead
Take a look at ui-bootstrapโ€™s directives at
https://github.com/angular-
ui/bootstrap/tree/master/src
Testing
Faster Bug Tracking
Jasmine Given
http://www.airpair.com/angularjs/workshops/u
nit-testing-angularjs
describe("assigning stuff to this", function() {
Given(function() { this.number = 24; });
Given(function() { this.number++; });
When(function() { this.number *= 2; });
Then(function() { expect(this.number).toBe(50) });
});
Links
https://thinkster.io/angulartutorial/a-better-
way-to-learn-angularjs/
http://chieffancypants.github.io/angular-
loading-bar
http://angular-js.in
https://docs.google.com/document/d/1XXMvRe
O8-
Awi1EZXAXS4PzDzdNvV6pGcuaF4Q9821Es/pub
Questions

More Related Content

PDF
Building Android apps with Parse
PPTX
The battle of Protractor and Cypress - RunIT Conference 2019
PDF
Crossing platforms with JavaScript & React
PPTX
Angular js
PDF
Node.js and Parse
PDF
Parse cloud code
PDF
AngularJS Basics with Example
PDF
Developing iOS REST Applications
ย 
Building Android apps with Parse
The battle of Protractor and Cypress - RunIT Conference 2019
Crossing platforms with JavaScript & React
Angular js
Node.js and Parse
Parse cloud code
AngularJS Basics with Example
Developing iOS REST Applications
ย 

What's hot (20)

PDF
SwiftUI and Combine All the Things
PDF
Making connected apps with BaaS (Droidcon Bangalore 2014)
PPTX
Introduction to MongoDB
PPTX
Angular 4 with firebase
PPTX
AngularJs
PDF
Introduction to App Engine Development
PDF
Firebase for Apple Developers
PDF
Getting Started with Combine And SwiftUI
PDF
Parse: A Mobile Backend as a Service (MBaaS)
PDF
๏ + ๏”ฅ = โค๏ธ (Firebase for Apple Developers) at Swift Leeds
PDF
Automated testing by Richard Olrichs and Wilfred vd Deijl
PPTX
What's new for developers in Dynamics 365 v9: Client API enhancement
PDF
Google App Engine Developer - Day2
PDF
Android L02 - Activities and Adapters
PPTX
Wordpress hooks
PDF
Introduce to PredictionIO
ODP
AngularJs Crash Course
PPTX
Leveraging Azure Search in Your Application
PPTX
Firebase ng2 zurich
PDF
#ajn3.lt.marblejenka
SwiftUI and Combine All the Things
Making connected apps with BaaS (Droidcon Bangalore 2014)
Introduction to MongoDB
Angular 4 with firebase
AngularJs
Introduction to App Engine Development
Firebase for Apple Developers
Getting Started with Combine And SwiftUI
Parse: A Mobile Backend as a Service (MBaaS)
๏ + ๏”ฅ = โค๏ธ (Firebase for Apple Developers) at Swift Leeds
Automated testing by Richard Olrichs and Wilfred vd Deijl
What's new for developers in Dynamics 365 v9: Client API enhancement
Google App Engine Developer - Day2
Android L02 - Activities and Adapters
Wordpress hooks
Introduce to PredictionIO
AngularJs Crash Course
Leveraging Azure Search in Your Application
Firebase ng2 zurich
#ajn3.lt.marblejenka
Ad

Viewers also liked (7)

PPTX
ECMAScript 2015
PPTX
HTML5 Graphics
PPTX
Introduction to React
PPTX
Sencha Touch
PDF
An Introduction to Sencha Touch
PPTX
Combining Angular and React Together
PDF
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
ECMAScript 2015
HTML5 Graphics
Introduction to React
Sencha Touch
An Introduction to Sencha Touch
Combining Angular and React Together
32 Ways a Digital Marketing Consultant Can Help Grow Your Business
Ad

Similar to Tips for Angular Applications (20)

PPT
AngularJS Mobile Warsaw 20-10-2014
PPTX
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
PPTX
Writing HTML5 Web Apps using Backbone.js and GAE
PDF
Prototyping applications with heroku and elasticsearch
ย 
PDF
Django
PPTX
SharePoint Saturday Atlanta 2015
DOCX
Angular js
PDF
"Angular.js Concepts in Depth" by Aleksandar Simoviฤ‡
PPTX
Angular JS deep dive
ย 
PPTX
Introduction to ElasticSearch
ย 
PPTX
Basics of AngularJS
KEY
Summer - The HTML5 Library for Java and Scala
PDF
ANGULARJS.pdf
ย 
PPTX
AngularJs Workshop SDP December 28th 2014
PDF
Why ruby on rails
PDF
Angular.js Primer in Aalto University
ย 
PPTX
Meteor Day Talk
PPTX
Javascript first-class citizenery
ย 
PPTX
angularJs Workshop
PDF
Ako prepojiลฅ aplikรกciu s Elasticsearch
ย 
AngularJS Mobile Warsaw 20-10-2014
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
Writing HTML5 Web Apps using Backbone.js and GAE
Prototyping applications with heroku and elasticsearch
ย 
Django
SharePoint Saturday Atlanta 2015
Angular js
"Angular.js Concepts in Depth" by Aleksandar Simoviฤ‡
Angular JS deep dive
ย 
Introduction to ElasticSearch
ย 
Basics of AngularJS
Summer - The HTML5 Library for Java and Scala
ANGULARJS.pdf
ย 
AngularJs Workshop SDP December 28th 2014
Why ruby on rails
Angular.js Primer in Aalto University
ย 
Meteor Day Talk
Javascript first-class citizenery
ย 
angularJs Workshop
Ako prepojiลฅ aplikรกciu s Elasticsearch
ย 

Recently uploaded (20)

PPTX
artificial intelligence overview of it and more
PDF
An introduction to the IFRS (ISSB) Stndards.pdf
PPTX
E -tech empowerment technologies PowerPoint
PDF
Cloud-Scale Log Monitoring _ Datadog.pdf
PPTX
Introuction about WHO-FIC in ICD-10.pptx
PDF
Slides PDF The World Game (s) Eco Economic Epochs.pdf
PPTX
SAP Ariba Sourcing PPT for learning material
PDF
๐Ÿ’ฐ ๐”๐Š๐“๐ˆ ๐Š๐„๐Œ๐„๐๐€๐๐†๐€๐ ๐Š๐ˆ๐๐„๐‘๐Ÿ’๐ƒ ๐‡๐€๐‘๐ˆ ๐ˆ๐๐ˆ ๐Ÿ๐ŸŽ๐Ÿ๐Ÿ“ ๐Ÿ’ฐ
ย 
PPTX
Slides PPTX World Game (s) Eco Economic Epochs.pptx
PPTX
artificialintelligenceai1-copy-210604123353.pptx
ย 
PPT
Design_with_Watersergyerge45hrbgre4top (1).ppt
DOCX
Unit-3 cyber security network security of internet system
PPTX
Digital Literacy And Online Safety on internet
PDF
SASE Traffic Flow - ZTNA Connector-1.pdf
PDF
Automated vs Manual WooCommerce to Shopify Migration_ Pros & Cons.pdf
PPTX
Introduction about ICD -10 and ICD11 on 5.8.25.pptx
PPTX
international classification of diseases ICD-10 review PPT.pptx
PPTX
June-4-Sermon-Powerpoint.pptx USE THIS FOR YOUR MOTIVATION
PDF
Vigrab.top โ€“ Online Tool for Downloading and Converting Social Media Videos a...
PDF
Best Practices for Testing and Debugging Shopify Third-Party API Integrations...
artificial intelligence overview of it and more
An introduction to the IFRS (ISSB) Stndards.pdf
E -tech empowerment technologies PowerPoint
Cloud-Scale Log Monitoring _ Datadog.pdf
Introuction about WHO-FIC in ICD-10.pptx
Slides PDF The World Game (s) Eco Economic Epochs.pdf
SAP Ariba Sourcing PPT for learning material
๐Ÿ’ฐ ๐”๐Š๐“๐ˆ ๐Š๐„๐Œ๐„๐๐€๐๐†๐€๐ ๐Š๐ˆ๐๐„๐‘๐Ÿ’๐ƒ ๐‡๐€๐‘๐ˆ ๐ˆ๐๐ˆ ๐Ÿ๐ŸŽ๐Ÿ๐Ÿ“ ๐Ÿ’ฐ
ย 
Slides PPTX World Game (s) Eco Economic Epochs.pptx
artificialintelligenceai1-copy-210604123353.pptx
ย 
Design_with_Watersergyerge45hrbgre4top (1).ppt
Unit-3 cyber security network security of internet system
Digital Literacy And Online Safety on internet
SASE Traffic Flow - ZTNA Connector-1.pdf
Automated vs Manual WooCommerce to Shopify Migration_ Pros & Cons.pdf
Introduction about ICD -10 and ICD11 on 5.8.25.pptx
international classification of diseases ICD-10 review PPT.pptx
June-4-Sermon-Powerpoint.pptx USE THIS FOR YOUR MOTIVATION
Vigrab.top โ€“ Online Tool for Downloading and Converting Social Media Videos a...
Best Practices for Testing and Debugging Shopify Third-Party API Integrations...

Tips for Angular Applications

  • 1. ยฉ Copyright SELA software & Education Labs Ltd. | 14-18 Baruch Hirsch St Bnei Brak, 51202 Israel | www.selagroup.com SELA DEVELOPER PRACTICE MAY 31, 2015 โ€“ JUNE 4, 2015 Sebastian Pederiva Tips for Angular Applications Senior Consultant sebastianp@sela.co.il @spederiva tiny.cc/SebastianBlog
  • 3. Project Structure Roll your own Angular Seed https://github.com/angular/angular- seed
  • 5. Add Suffix to the file names Easy to read and understand Essential for โ€œcomponent typeโ€ structure Help make better automation and testing product-list.ctrl.js product-list.tpl.html product-list.fltr.js product-list.fctry.js product-list.srv.js product-list.const.js product-list.val.js
  • 6. Separate to Modules var corelist = app.module("app.core.list", []); corelist.controller("app.core.list.listCtrl", ...) angular.module(โ€œapp.common.services") .service("myApp.common.services.product"
  • 7. Golden Rules Controllers should never refer to any DOM elements Controllers should call services vs. holding too much business logic Avoid $rootScope, try to use services instead Expression {{}} vs ng-cloak
  • 8. Minimizing Angular Files Minimizing process will replace variable names compromising the dependency injection someModule.controller('MyController', ['$scope', function($scope) { $scope.name = "Sebastian"; }]); someModule.controller('MyController', function ($scope) { $scope.name = "Sebastian"; }); someModule.controller('MyController', function (a) { a.name = "Sebastian"; });
  • 9. One Time Binding Use double colon :: https://code.angularjs.org/1.3.15/docs/guide/e xpression#one-time-binding For previous versions: https://github.com/Pasvaz/bindonce <p id="one-time-binding-example"> One time binding: {{::name}} </p>
  • 10. Controller Inheritance app.controller("ChildCtrl", ["$scope", function ($scope) { $scope.childText = "childText" $scope.text = "childTextโ€ }]); app.controller("ParentCtrl", ["$scope", function ($scope) { $scope.parentText = "parentText" $scope.text = "parentTextโ€ }]); <div ng-controller="ParentCtrlโ€> <div ng-controller="ChildCtrlโ€> {{parentText}} <br/> {{childText}} <br/> {{text}} </div> </div>
  • 11. Controller Inheritance app.controller("ChildCtrl", function ($scope, $controller) { $controller("ParentCtrl", {$scope: $scope}); $scope.childText = "childText"; $scope.text = "childText"; }); app.controller("ParentCtrl", ["$scope", function ($scope) { $scope.parentText = "parentText" $scope.text = "parentTextโ€ }]); <div ng-controller="ChildCtrlโ€> {{parentText}} <br/> {{childText}} <br/> {{text}} </div>
  • 12. Avoid Watchers $watch occurs when the users clicks on an item, not when the model changes Consider using events instead Minimize use watchers Angular uses dirty checking to keep track of all the changes in app
  • 13. $watch() vs. $watchCollection() $watch has 3 parameters Use $watchCollection, it only checks the first layer of objectโ€™s properties http://www.bennadel.com/blog/2566-scope- watch-vs-watchcollection-in-angularjs.htm http://plnkr.co/edit/Pbvo6AqME081rZ2RVKDU? p=preview
  • 14. ng-repeat, track when possible ngRepeat does not allow duplicate items in arrays Track by to increase performance Default tracking <div ng-repeat=โ€item in collection track by $id(obj)โ€> Own tracking <div ng-repeat=โ€item in collection track by item.idโ€> https://docs.angularjs.org/api/ng/directive/ngR epeat#tracking-and-duplicates
  • 15. ng-repeat How many times will getPrice function be called? Use watch collection to calculate everything when the controller is first invoked <tr ng-repeat="item in items"> <td>{{item.name}}</td> <td>{{item.description}}</td> <td>{{getPrice(item.id)}}</td> </tr>
  • 16. ng-repeat cont <tr ng-repeat="item in items"> <td>{{item.name}}</td> <td>{{item.description}}</td> <td>{{item.price}}</td> </tr> $scope.$watchCollection('items', function (newItems) { for (var i = 0; i < newItems.length; i++) { newItems[i].price = getPrice(newItems.id); } $scope.items = newItems; });
  • 17. Avoid ng-repeat for infinite scroll Memory Leaks Performance problem Possible solution: http://www.williambrownstreet.net/blog/2013/0 7/angularjs-my-solution-to-the-ng-repeat- performance-problem
  • 18. Debounce ng-model Lot of updates? https://docs.angularjs.org/api/ng/directive/ng ModelOptions <input ng-model="nameโ€ ng-model-options="{ debounce: 500 }โ€ />
  • 19. Use ng-if instead of ng-show ng-show will render an element, and use display:none to hide it ng-if will actually removes the element from DOM, and will re-create it, if itโ€™s needed.
  • 20. Promise you use Promises Prefer Promises Over Callbacks Follow The โ€˜...ingโ€™ Convention Clear Indication Youโ€™re getting a Promise function gettingUsers(){ return $http()... } gettingUsers() .success() .error()
  • 21. Destroying Memory Leaks Use $scope.$on('$destroy', โ€ฆ) Remove handlers Clean up resources which wonโ€™t be garbage collected automatically module.controller("TestController", function ($scope, $timeout) { var onTimeout = function () { $scope.value += 1; timer = $timeout(onTimeout, 1000); }; var timer = $timeout(onTimeout, 1000); $scope.value = 0; $scope.$on("$destroy", function () { if (timer) { $timeout.cancel(timer); } }); });
  • 22. Managing the Timeโ€ฆuse moment.js https://github.com/urish/angular-moment <span am-time-ago="message.time"> </span>
  • 26. Logging Avoid using console.log in your controllers Use $log instead $log can be extended to provide additional logging capabilities
  • 27. Forget jQuery Exists jQuery -- Use angular.element instead of $() selector -- Search for a jQuery-equivalent instead ยป Examples -- html(), text(), val() ยป Ask whether you can use directives instead Take a look at ui-bootstrapโ€™s directives at https://github.com/angular- ui/bootstrap/tree/master/src
  • 28. Testing Faster Bug Tracking Jasmine Given http://www.airpair.com/angularjs/workshops/u nit-testing-angularjs describe("assigning stuff to this", function() { Given(function() { this.number = 24; }); Given(function() { this.number++; }); When(function() { this.number *= 2; }); Then(function() { expect(this.number).toBe(50) }); });

Editor's Notes

  • #7: Faster Unit Testing Gives Context Easier To Remove Parts Of The App
  • #8: "How do I pass things between controllers?" --- ...probably means that you are doing things wrong Theย ngCloakย directive is used to prevent the Angular html template from being briefly displayed by the browser in its raw (uncompiled) form while your application is loading
  • #10: Angular 1.3 addedย :: Angular will wait for a value to stabilize after itโ€™s first series of digest cycles, and will use that value to render the DOM element. After that, Angular will remove the watcher forgetting about that binding
  • #13: Minimize use watchers Angular uses dirty checking to keep track of all the changes in app through every watcher to check if they need to be updated If one of the watcher is relied upon by another watcher, Angular would have to re-run the digest cycle again
  • #14: Third parameters is deep eval $watchCollection acts almost like $watch with a 3rd parameter except it only checks the first layer of objectโ€™s properties
  • #15: ngRepeatย does not allow duplicate items in arrays. This is because when there are duplicates, it is not possible to maintain a one-to-one mapping between collection items and DOM elements. ngRepeatย will not have to rebuild the DOM elements for items it has already rendered
  • #18: Because ng-repeat uses watchers ng-repeat creates bad performance and AngularJS is getting slower with more than 2000-2500 two-way bindings to watch
  • #28: DOM traversal is also problematic Separation of Concerns Overkiller
  • #29: Using TDD for Better Engineering