SlideShare a Scribd company logo
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
Welcome
to
JavaScripters
Community for Connect, Learn, Share & Explore your knowledge base
http://www.javascripters.org
Email: pune.javascripters@gmail.com
Twitter: @javascripters_
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
2
About JavaScripters
JavaScripters is an initiative taken for front-end engineers community to share and gain JavaScript
basic and advance knowledge along with moto to connect all javascripters together.
We conduct technical discussion forums, sessions, workshops, trainings and knowledge sharing
meetups around the city, for all front-end / UI engineers on core & advance(object oriented) level
javascript concepts, along with all latest javascript frameworks like AngularJS, NodeJs, emberJs,
TypeScript, ReactJs technologies by experts.
• Since : April 2015
• Members : Around 2500+
• Speakers & Mentors : 17
• Events/ Meetup Conducted: 5
• Feature Planned Events : 10 events confirmed till December
2016
Our initiatives:
WhatsApp Groups
Meetup Groups
JavaScriptes
PuneJs
HTML5-Web-Mobile-Development-Meetup
Pune-UX-UI-Engineers
WebF
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
List of upcoming events
3
1.Developing JavaScript Code for efficiency
2.Immutable and Functional JavaScript
3.Introduction of Design thinking for front-end Engineers
4.React JS with Material design
5.Introduction to Angular 2.x
6.Practice with TypeSpcript
7.Introduction to ES6
8.Automated javascript workflow with Gulp
9.NodeJs practice session
1. Total (3) online webinar under planning
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
Our Sponsor
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
• Software Engineer at TSS Consultancy PVT LTD
• Loves to code in .Net + Angular
• Active Angular community contributor
• Microsoft MVP
• Stackoverflow topuser from India
• Angular 1 & Angular 2 topuser on Stackoverflow
• Invited as a honor of guest in ng-conf USA(UTAH)
• etc...
About Speaker
Pankaj Parkar
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
Mention twitter handle
• @javascripters_
• @pankajparkar
• @angularjs
With #meetup #pune #angular #javascript tag.
Let’s have #tweet
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
• Not have dot in models.
• Lack of modularity
• Polluting $rootScope isn’t good
idea
• Cleanup async events
• Inserting DOM into current
• ng-if vs ng-show
12 common mistakes made by Angular Developers
• Folder structure
• Follow Dependency Injection
pattern
• Utilization of jQuery
• Try to utilize form validation.
• Avoid usage of watch.
• Avoid deferred anti pattern.
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
• Having scope variable without using Dot Rule can break scope bindings
• You must be wondering, What is Dot Rule?
When new prototypically inherited scope gets created inside child scope, that time primitive type
variable copy gets copied down to the child scope & reference type value are taken with there
references. If the inner scope changes primitive value it doesn't update the parent value copy.
Where as if you change reference datatype value, it will change object value of parent object.
<div ng-app="app" ng-controller="outerCtrl" class="border">
<p>Outer Controller Scope:</p>
<p>{{ foo }}</p>
<div ng-if="showInnerContent" class="border">
<p>Inner Scope</p>
<p>{{ foo }}</p>
<button ng-click="foo='Something Else'">
Change Foo
</button>
</div>
</div>
1. Not have dot in models
Demo
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
Lets define object inside a controller like "$scope.model = {};" and place all property in it, here we're going to put `foo` in that.
<div ng-app="app" ng-controller="outerCtrl" class="border">
<input ng-model="model.foo" />
<p>Outer Controller Scope:</p>
<p>{{ model.foo }}</p>
<div ng-if="showInnerContent" class="border">
<p>Inner Scope</p>
<p>{{ model.foo }}</p>
<button ng-click="foo='Something Else'">
Change Foo from inner scope
</button>
</div>
</div>
1. a) Not have dot in model ctd..
Demo Plunkr
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
• Another correct way to resolve binding issue is use `controllerAs` pattern where scope binding issue
solved.
• controllerAs syntax does remove scope dependency from that controller.
<div ng-app="app" ng-controller="outerCtrl as vm" class="border">
<input ng-model="vm.foo"/>
<p>Outer Controller Scope:</p>
<p>{{ vm.foo }}</p>
<div ng-if="vm.showInnerContent" class="border">
<p>Inner Scope</p>
<p>{{ vm.foo }}</p>
<button ng-click="vm.foo='Something Else'">
Change Foo from inner scope
</button>
</div>
</div>
Demo
1. b) Not have dot in model ctd..
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
• Generally what people do is, they create a application with single main module & keep on putting other stuff in the same
module.
• After certain time for large enterprise application, you will come a mess.
var app = angular.module('app', []);
app.controller('myCtrl', function($scope) {
//controller data
//controller should be as thin as possible
//don’t ever think of DOM manipulation from controller
});
app.service('sharedService', function() {
//service code only.
});
//so other angular comonents like factory, filter, etc.
//would also gets added inside "app" module.
//In large scale application it become difficult to see which code appears to be where
2. Lack of modularity
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
• For handling such case you could create a different different module inside your application. Consider module
as namespace of application. By looking at module you could define the nature of things lies inside it.
• Let's try to make thing modular by creating module & putting up there respective components in it.
//module for services
angular.module('myApp.services', []);
//module for services
angular.module('myApp.controllers', ['myApp.services']);
//module for services
angular.module('myApp.filters', []);
//module for services
angular.module('myApp.pipes', []);
//module for services
angular.module('myApp.shareService', []);
//can be combine to one our main application
angular.module('app', [
'myApp.services', 'myApp.controllers', 'myApp.pipes', 'myApp.services', 'myApp.shareService’
]);
2. Lack of modularity ctd.
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
• Generally developer tends to prefer shortest way with what they do. Most of the time they use $rootScope for
sharing data amongst various application component.
• Polluting $rootScope is considered as bad practice.
• Why it’s a bad practice?
• Once data pushed inside $rootScope, its applicable inside each application component.
• Any changes in the $rootScope would run a digest cycle and unnecessarily one digest cycle will that will
refresh all the bindings.
• Using $rootScope you can't maintain that abstraction layer.
3. Polluting $rootScope.
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
• When you have async events (like $timeout, $interval, etc.) inside controller and after route navigation occurs
you moved on different page with its own template & controller those events doesn't get removed. Generally
developer missed this thing while building application.
• Because behind the scene these events have been added inside Event Loop to process them
asynchronously.
• For removing them you've to call `cancelInterval` /`cancelTimeout`/`deregisterEvent`
4. Cleaning up async events
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
• To remove them manually you can need to handle such situation on controller destruction
• While navigating from one page another page, based on router definition it loads new template & associate
controller with it. Exactly before removing controller it it emits `$destroy` event over scope.
app.controller('myCtrl', function($scope, $element) {
var count = 0;
var interval = $interval(function() {
console.log(++count)
}, 5000)
$scope.$on('$destroy', function(event, data) {
$interval.cance(interval);
});
//since $scope would get remove once you use controllerAs
//when you are using controllerAs pattern, use below thing
$element.on('$destroy', function(event, data) {
$interval.cance(interval);
});
});
4. Cleaning up async events cntd.
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
• Whenever user wants to add new DOM inside a DOM tree they do go for plain jQuery.
$scope.output = 'Result';
var template = '<div>{{output}}</div>';
angular.element(document.getElementById('testDiv')).append(template);
• By doing above what developer do expect is div to show "Result" value on HTML. But this doesn't happen in
angular.
• You need to compile a DOM with $compile service before injecting a DOM on page.
$scope.output = 'Result';
var template = '<div>{{output}}</div>';
var compiledTemplate = $compile(template)($scope);
angular.element(document.getElementById('testDiv')).append(compiledTemplate);
5. Inserting new DOM
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
• Most of the developer uses ng-show/ng-hide every place where they want to show/hide DOM based on
expression.
• How ng-show and ng-if works?
• That's what the problem is with ng-show, because when it hides DOM it present their in DOM tree which is
bad.
• But don't blindly replace ng-show with ng-if, after changing it to ng-if make sure 1st point is implemented.
<div ng-show="showGrids">
<pm-kendo-grid></pm-kendo-grid>
<pm-dev-express-grid></pm-dev-express-grid>
<pm-ig-grid></pm-ig-grid>
<div>
Another html content
</div>
<div>
6. ng-if vs ng-show
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
• Generally most of the people follow MVC folder structure while organising angular code.
7. Folder Structure
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
• Per convention do follow feature wise folder structure
• It would make you one step ahead for angular 2 migration.
7. Folder Structure ctd.
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
• First lets see what is dependency injection
There are 3 types of DI Annotation
1. Inline Array Annotation
2. $inject property Annotation
3. Implicit Annotation
8. Follow Dependency Injection
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
1. Inline array annotation
Here we 1st create an array with dependency we inject dependencies in string & then use the same in function
function myController($scope, myService) {
//Awesome controller code here
}
someModule.controller('myController', ['$scope', 'myService', MyController]);
function myService($log) {
//Awesome service code here
}
someModule.service('myService', ['$log', myService]);
8.1 Follow Dependency Injection ctd.
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
2. $inject Property annotation
Here we 1st create an array with dependency we inject dependencies in string & then use the same in function
function myController($scope, myService) {
//Awesome controller code here
}
myController.$inject = ['$scope', 'myService'];
someModule.controller('myController', myController);
function myService($log) {
//Awesome service code here
}
myService.$inject = ['$log'];
someModule.service('myService', myService);
8.2 Follow Dependency Injection ctd.
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
3. Implicit annotation
Here we 1st create an array with dependency we inject dependencies in string & then use the same in function
function myController($scope, myService) {
//Awesome controller code here
}
someModule.controller('myController', myController);
function myService($log) {
//Awesome service code here
}
someModule.service('myService', myService);
8.3 Follow Dependency Injection ctd.
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
“Developer do use more simplest thing”
function myController($scope, myService) {
//Awesome controller code here
}
someModule.controller('myController', myController);
But what happens is when you minify such files to reduce number of roundtrip to server, this DI technique
messed up minification.
function myController(a,b){};someModule.controller('myController', myController);
• You can see that minified file has changed the dependency name in function. from `$scope, myService` to
`a,b`. This where error will appear on the page `aProvider is missing`.
• Thus you should use Array inline annotation when injecting dependency.
8. Follow Dependency Injection ctd.
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
• Angular has built in small version of jQuery aka “jQLite”
• Try to avoid use of jQuery, as it seems to be less performant
• Whenever you are trying use any jQuery plugin wrap it inside a directive link function, because it provides a
controller over DOM before & after element compilation by Angular
9. Utilization of jQuery
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
• Don’t write a custom code for validation purpose, like most of the developer check each property value inside
DOM. You can utilize validation feature provided by angular out of the box
• Some validation property
• $pristine (ng-pristine)
• $error
• $dirty (ng-dirty)
• $submitted (ng-submitted)
• $valid (ng-valid)
• $invalid (ng-invalid)
I’d highly recommend to look into form API from angular docs
10. Try to utilize form validation
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
• Watcher gets evaluated its expression of each digest cycle.
• Watcher count more than 2000 on page can leads to performance impact on the page.
• Even data binding ({{myData}}) on the page considered as watcher
$scope.$watch('myVariable', function(newValue, oldValue) {
console.log('newValue ' + newValue);
console.log('oldValue ' + oldValue);
}, true);
• Watcher has been deprecated from angular 2, so you shouldn’t be writing watcher going forward.
• You can use alternative way instead of watcher.
• As per new syntax you can use $doCheck lifecycle hook of component.
• You can follow event $broadcast & $emit to communicate with other controller/component
• You could us $viewChangesListner of ngModel controller to fire desired method (by requiring `ngModel`
directive in `require` option)
• You could also take an use of $parser & $formatters on ngModel (by requiring `ngModel` directive in
`require` option)
11. Avoid usage of watcher
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
• Angular used q library to use promise pattern.
• Generally what people do is while making an API call the to create a custom defer & resolve it by there own
like below
function getData() {
var deferred = $q.defer();
$http.get(url)
.then(function(response) {
//console.log(response.data);
deferred.resolve(resolve.data); //resolve promise
}, function(error) {
deferred.reject(resolve.data); //reject promise
})
return deferred.promise;
}
getData().then(function(data){
console.log(data);
}, function(error){
console.log(error);
})
12. Avoid deferred antipattern.
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
• When making an ajax we do use $http in Angular
• $http all methods returns promise internally, you don’t need to create explicit promise yourself.
• Previous code can be minimize
function getData() {
return $http.get(url); //utilized promise return by angular $http API
}
getData().then(function(data){
console.log(data);
}, function(error){
console.log(error);
})
• Likewise other library $resource, Restangular, etc. do the same thing. They return promise when it makes an
ajax call.
12. Avoid deferred antipattern.
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
Thank You
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
Question & Answer
JS
JavaScripters www.javascripters.org
JS
JavaScripters www.javascripters.org
Registers for upcoming events
3
2
1.Developing JavaScript Code for efficiency
2.Immutable and Functional JavaScript
3.Introduction of Design thinking for front-end Engineers
4.React JS with Material design
5.Introduction to Angular 2.x
6.Practice with TypeSpcript
7.Introduction to ES6
8.Automated javascript workflow with Gulp
9.NodeJs practice session
1. Total (3) online webinar under planning

More Related Content

What's hot (20)

PPTX
Practical AngularJS
Wei Ru
 
PDF
Advanced Tips & Tricks for using Angular JS
Simon Guest
 
DOCX
Different way to share data between controllers in angular js
codeandyou forums
 
PPTX
AngularJS in 60ish Minutes
Dan Wahlin
 
DOCX
Built in filters
Brajesh Yadav
 
PPTX
AngularJs
syam kumar kk
 
DOCX
Filters in AngularJS
Brajesh Yadav
 
PPTX
Angularjs Basics
Anuradha Bandara
 
PPTX
Introduction to Backbone.js & Marionette.js
Return on Intelligence
 
PPTX
AngularJS Beginners Workshop
Sathish VJ
 
PDF
AngularJS - Overcoming performance issues. Limits.
Dragos Mihai Rusu
 
PDF
Angular js routing options
Nir Kaufman
 
PDF
Angular JS blog tutorial
Claude Tech
 
PDF
Marionette: the Backbone framework
frontendne
 
PDF
AngularJS Framework
Barcamp Saigon
 
PDF
Introduction to AngularJS
Jussi Pohjolainen
 
PPTX
Angular JS - Introduction
Sagar Acharya
 
PDF
AngularJS best-practices
Henry Tao
 
PPTX
Building an End-to-End AngularJS Application
Dan Wahlin
 
PPTX
AngularJs presentation
Phan Tuan
 
Practical AngularJS
Wei Ru
 
Advanced Tips & Tricks for using Angular JS
Simon Guest
 
Different way to share data between controllers in angular js
codeandyou forums
 
AngularJS in 60ish Minutes
Dan Wahlin
 
Built in filters
Brajesh Yadav
 
AngularJs
syam kumar kk
 
Filters in AngularJS
Brajesh Yadav
 
Angularjs Basics
Anuradha Bandara
 
Introduction to Backbone.js & Marionette.js
Return on Intelligence
 
AngularJS Beginners Workshop
Sathish VJ
 
AngularJS - Overcoming performance issues. Limits.
Dragos Mihai Rusu
 
Angular js routing options
Nir Kaufman
 
Angular JS blog tutorial
Claude Tech
 
Marionette: the Backbone framework
frontendne
 
AngularJS Framework
Barcamp Saigon
 
Introduction to AngularJS
Jussi Pohjolainen
 
Angular JS - Introduction
Sagar Acharya
 
AngularJS best-practices
Henry Tao
 
Building an End-to-End AngularJS Application
Dan Wahlin
 
AngularJs presentation
Phan Tuan
 

Viewers also liked (20)

PPTX
JavaScripters Event on Sep 10, 2016 · 10:30 AM: Sass
JavaScripters Community
 
PPTX
JavaScripters Event Sep 17, 2016 · 2:00 PM: Scalable Javascript Design Patterns
JavaScripters Community
 
PPTX
Poliedros
Gcticomaria
 
PPTX
555858
yeeeaa
 
PPTX
El Comercio
orianaalejandratoro99
 
DOCX
Define que es un cliente
Juan Carlos Flores Parra
 
PPTX
Grooming
stylesebas7
 
PPTX
Tarea del seminario 5
sebastian101995
 
DOCX
Transcript Dr. Obumneke Amadi - Health Literacy
Discover Health Global Initiative
 
DOCX
Trabajo tecnología
Rafa García Márquez
 
PDF
profile-3p2
Supoj Taweerat
 
DOCX
PARCIAL FINAL
Yarlys Muñoz
 
DOC
Informe de COMUEDA, de fecha 23/05/2014 Asistencia a familias afectadas por l...
Intendente, de la la ciudad de Asuncion, capital de la República del Paraguay
 
PDF
Copia de diferido territorial de Guatemala
Vilman Janneth Carrera Davila
 
PPTX
Tarea del seminario 3
sebastian101995
 
DOCX
LAMARAN YOPIE FERDIAN 081220209669
yopie ferdian
 
PPTX
Las Tic.
maykaleja
 
PDF
Símbolos patrios de perú pdf
Gleyni Lopez Meza
 
PPTX
Social media Applications in Medicine and Health Care
Oscar Ramos Torres
 
JavaScripters Event on Sep 10, 2016 · 10:30 AM: Sass
JavaScripters Community
 
JavaScripters Event Sep 17, 2016 · 2:00 PM: Scalable Javascript Design Patterns
JavaScripters Community
 
Poliedros
Gcticomaria
 
555858
yeeeaa
 
El Comercio
orianaalejandratoro99
 
Define que es un cliente
Juan Carlos Flores Parra
 
Grooming
stylesebas7
 
Tarea del seminario 5
sebastian101995
 
Transcript Dr. Obumneke Amadi - Health Literacy
Discover Health Global Initiative
 
Trabajo tecnología
Rafa García Márquez
 
profile-3p2
Supoj Taweerat
 
PARCIAL FINAL
Yarlys Muñoz
 
Informe de COMUEDA, de fecha 23/05/2014 Asistencia a familias afectadas por l...
Intendente, de la la ciudad de Asuncion, capital de la República del Paraguay
 
Copia de diferido territorial de Guatemala
Vilman Janneth Carrera Davila
 
Tarea del seminario 3
sebastian101995
 
LAMARAN YOPIE FERDIAN 081220209669
yopie ferdian
 
Las Tic.
maykaleja
 
Símbolos patrios de perú pdf
Gleyni Lopez Meza
 
Social media Applications in Medicine and Health Care
Oscar Ramos Torres
 
Ad

Similar to JavaScripters Event Oct 22, 2016 · 2:00 PM: Common Mistakes made by Angular Developers (20)

PDF
AngularJS 101
Houssem Yahiaoui
 
PPTX
Intro to AngularJs
SolTech, Inc.
 
PDF
What Is Angular 2 | Angular 2 Tutorial For Beginners | Angular Training | Edu...
Edureka!
 
PPTX
AngularJS One Day Workshop
Shyam Seshadri
 
PDF
Ionic framework one day training
Troy Miles
 
PDF
AngularJS Basics
Ravi Mone
 
PDF
Getting Started With AngularJS
Edureka!
 
PDF
Javascript: the important bits
Chris Saylor
 
PDF
AngularJS for Beginners
Edureka!
 
PPTX
Angular js
Mauro Servienti
 
PDF
Requirements Bazaar powered by AngularJS and Polymer - Talk at Google Develop...
IstvanKoren
 
PDF
Getting Started with AngularJS
Edureka!
 
PPTX
Training On Angular Js
Mahima Radhakrishnan
 
PDF
AngularJS Workshop
Gianluca Cacace
 
PDF
Resources and relationships at front-end
Wingify Engineering
 
PPSX
Angular js
Arun Somu Panneerselvam
 
PDF
Ultimate Introduction To AngularJS
Jacopo Nardiello
 
PPTX
Understanding angular js
Aayush Shrestha
 
PDF
AngularJS in practice
Eugene Fidelin
 
PPT
introduction to Angularjs basics
Ravindra K
 
AngularJS 101
Houssem Yahiaoui
 
Intro to AngularJs
SolTech, Inc.
 
What Is Angular 2 | Angular 2 Tutorial For Beginners | Angular Training | Edu...
Edureka!
 
AngularJS One Day Workshop
Shyam Seshadri
 
Ionic framework one day training
Troy Miles
 
AngularJS Basics
Ravi Mone
 
Getting Started With AngularJS
Edureka!
 
Javascript: the important bits
Chris Saylor
 
AngularJS for Beginners
Edureka!
 
Angular js
Mauro Servienti
 
Requirements Bazaar powered by AngularJS and Polymer - Talk at Google Develop...
IstvanKoren
 
Getting Started with AngularJS
Edureka!
 
Training On Angular Js
Mahima Radhakrishnan
 
AngularJS Workshop
Gianluca Cacace
 
Resources and relationships at front-end
Wingify Engineering
 
Ultimate Introduction To AngularJS
Jacopo Nardiello
 
Understanding angular js
Aayush Shrestha
 
AngularJS in practice
Eugene Fidelin
 
introduction to Angularjs basics
Ravindra K
 
Ad

Recently uploaded (20)

PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PDF
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
PPTX
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
PPTX
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
PPTX
How Cloud Computing is Reinventing Financial Services
Isla Pandora
 
PPTX
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
PPTX
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
PDF
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PDF
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
PDF
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PDF
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
PPTX
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
PDF
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
PDF
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Thread In Android-Mastering Concurrency for Responsive Apps.pdf
Nabin Dhakal
 
Writing Better Code - Helping Developers make Decisions.pptx
Lorraine Steyn
 
Why Businesses Are Switching to Open Source Alternatives to Crystal Reports.pptx
Varsha Nayak
 
How Cloud Computing is Reinventing Financial Services
Isla Pandora
 
Transforming Mining & Engineering Operations with Odoo ERP | Streamline Proje...
SatishKumar2651
 
Equipment Management Software BIS Safety UK.pptx
BIS Safety Software
 
Mobile CMMS Solutions Empowering the Frontline Workforce
CryotosCMMSSoftware
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
Online Queue Management System for Public Service Offices in Nepal [Focused i...
Rishab Acharya
 
Beyond Binaries: Understanding Diversity and Allyship in a Global Workplace -...
Imma Valls Bernaus
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
Alexander Marshalov - How to use AI Assistants with your Monitoring system Q2...
VictoriaMetrics
 
Fundamentals_of_Microservices_Architecture.pptx
MuhammadUzair504018
 
Powering GIS with FME and VertiGIS - Peak of Data & AI 2025
Safe Software
 
유니티에서 Burst Compiler+ThreadedJobs+SIMD 적용사례
Seongdae Kim
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 

JavaScripters Event Oct 22, 2016 · 2:00 PM: Common Mistakes made by Angular Developers

  • 1. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org Welcome to JavaScripters Community for Connect, Learn, Share & Explore your knowledge base http://www.javascripters.org Email: [email protected] Twitter: @javascripters_
  • 2. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org 2 About JavaScripters JavaScripters is an initiative taken for front-end engineers community to share and gain JavaScript basic and advance knowledge along with moto to connect all javascripters together. We conduct technical discussion forums, sessions, workshops, trainings and knowledge sharing meetups around the city, for all front-end / UI engineers on core & advance(object oriented) level javascript concepts, along with all latest javascript frameworks like AngularJS, NodeJs, emberJs, TypeScript, ReactJs technologies by experts. • Since : April 2015 • Members : Around 2500+ • Speakers & Mentors : 17 • Events/ Meetup Conducted: 5 • Feature Planned Events : 10 events confirmed till December 2016 Our initiatives: WhatsApp Groups Meetup Groups JavaScriptes PuneJs HTML5-Web-Mobile-Development-Meetup Pune-UX-UI-Engineers WebF
  • 3. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org List of upcoming events 3 1.Developing JavaScript Code for efficiency 2.Immutable and Functional JavaScript 3.Introduction of Design thinking for front-end Engineers 4.React JS with Material design 5.Introduction to Angular 2.x 6.Practice with TypeSpcript 7.Introduction to ES6 8.Automated javascript workflow with Gulp 9.NodeJs practice session 1. Total (3) online webinar under planning
  • 5. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org • Software Engineer at TSS Consultancy PVT LTD • Loves to code in .Net + Angular • Active Angular community contributor • Microsoft MVP • Stackoverflow topuser from India • Angular 1 & Angular 2 topuser on Stackoverflow • Invited as a honor of guest in ng-conf USA(UTAH) • etc... About Speaker Pankaj Parkar
  • 6. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org Mention twitter handle • @javascripters_ • @pankajparkar • @angularjs With #meetup #pune #angular #javascript tag. Let’s have #tweet
  • 7. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org • Not have dot in models. • Lack of modularity • Polluting $rootScope isn’t good idea • Cleanup async events • Inserting DOM into current • ng-if vs ng-show 12 common mistakes made by Angular Developers • Folder structure • Follow Dependency Injection pattern • Utilization of jQuery • Try to utilize form validation. • Avoid usage of watch. • Avoid deferred anti pattern.
  • 8. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org • Having scope variable without using Dot Rule can break scope bindings • You must be wondering, What is Dot Rule? When new prototypically inherited scope gets created inside child scope, that time primitive type variable copy gets copied down to the child scope & reference type value are taken with there references. If the inner scope changes primitive value it doesn't update the parent value copy. Where as if you change reference datatype value, it will change object value of parent object. <div ng-app="app" ng-controller="outerCtrl" class="border"> <p>Outer Controller Scope:</p> <p>{{ foo }}</p> <div ng-if="showInnerContent" class="border"> <p>Inner Scope</p> <p>{{ foo }}</p> <button ng-click="foo='Something Else'"> Change Foo </button> </div> </div> 1. Not have dot in models Demo
  • 9. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org Lets define object inside a controller like "$scope.model = {};" and place all property in it, here we're going to put `foo` in that. <div ng-app="app" ng-controller="outerCtrl" class="border"> <input ng-model="model.foo" /> <p>Outer Controller Scope:</p> <p>{{ model.foo }}</p> <div ng-if="showInnerContent" class="border"> <p>Inner Scope</p> <p>{{ model.foo }}</p> <button ng-click="foo='Something Else'"> Change Foo from inner scope </button> </div> </div> 1. a) Not have dot in model ctd.. Demo Plunkr
  • 10. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org • Another correct way to resolve binding issue is use `controllerAs` pattern where scope binding issue solved. • controllerAs syntax does remove scope dependency from that controller. <div ng-app="app" ng-controller="outerCtrl as vm" class="border"> <input ng-model="vm.foo"/> <p>Outer Controller Scope:</p> <p>{{ vm.foo }}</p> <div ng-if="vm.showInnerContent" class="border"> <p>Inner Scope</p> <p>{{ vm.foo }}</p> <button ng-click="vm.foo='Something Else'"> Change Foo from inner scope </button> </div> </div> Demo 1. b) Not have dot in model ctd..
  • 11. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org • Generally what people do is, they create a application with single main module & keep on putting other stuff in the same module. • After certain time for large enterprise application, you will come a mess. var app = angular.module('app', []); app.controller('myCtrl', function($scope) { //controller data //controller should be as thin as possible //don’t ever think of DOM manipulation from controller }); app.service('sharedService', function() { //service code only. }); //so other angular comonents like factory, filter, etc. //would also gets added inside "app" module. //In large scale application it become difficult to see which code appears to be where 2. Lack of modularity
  • 12. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org • For handling such case you could create a different different module inside your application. Consider module as namespace of application. By looking at module you could define the nature of things lies inside it. • Let's try to make thing modular by creating module & putting up there respective components in it. //module for services angular.module('myApp.services', []); //module for services angular.module('myApp.controllers', ['myApp.services']); //module for services angular.module('myApp.filters', []); //module for services angular.module('myApp.pipes', []); //module for services angular.module('myApp.shareService', []); //can be combine to one our main application angular.module('app', [ 'myApp.services', 'myApp.controllers', 'myApp.pipes', 'myApp.services', 'myApp.shareService’ ]); 2. Lack of modularity ctd.
  • 13. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org • Generally developer tends to prefer shortest way with what they do. Most of the time they use $rootScope for sharing data amongst various application component. • Polluting $rootScope is considered as bad practice. • Why it’s a bad practice? • Once data pushed inside $rootScope, its applicable inside each application component. • Any changes in the $rootScope would run a digest cycle and unnecessarily one digest cycle will that will refresh all the bindings. • Using $rootScope you can't maintain that abstraction layer. 3. Polluting $rootScope.
  • 14. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org • When you have async events (like $timeout, $interval, etc.) inside controller and after route navigation occurs you moved on different page with its own template & controller those events doesn't get removed. Generally developer missed this thing while building application. • Because behind the scene these events have been added inside Event Loop to process them asynchronously. • For removing them you've to call `cancelInterval` /`cancelTimeout`/`deregisterEvent` 4. Cleaning up async events
  • 15. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org • To remove them manually you can need to handle such situation on controller destruction • While navigating from one page another page, based on router definition it loads new template & associate controller with it. Exactly before removing controller it it emits `$destroy` event over scope. app.controller('myCtrl', function($scope, $element) { var count = 0; var interval = $interval(function() { console.log(++count) }, 5000) $scope.$on('$destroy', function(event, data) { $interval.cance(interval); }); //since $scope would get remove once you use controllerAs //when you are using controllerAs pattern, use below thing $element.on('$destroy', function(event, data) { $interval.cance(interval); }); }); 4. Cleaning up async events cntd.
  • 16. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org • Whenever user wants to add new DOM inside a DOM tree they do go for plain jQuery. $scope.output = 'Result'; var template = '<div>{{output}}</div>'; angular.element(document.getElementById('testDiv')).append(template); • By doing above what developer do expect is div to show "Result" value on HTML. But this doesn't happen in angular. • You need to compile a DOM with $compile service before injecting a DOM on page. $scope.output = 'Result'; var template = '<div>{{output}}</div>'; var compiledTemplate = $compile(template)($scope); angular.element(document.getElementById('testDiv')).append(compiledTemplate); 5. Inserting new DOM
  • 17. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org • Most of the developer uses ng-show/ng-hide every place where they want to show/hide DOM based on expression. • How ng-show and ng-if works? • That's what the problem is with ng-show, because when it hides DOM it present their in DOM tree which is bad. • But don't blindly replace ng-show with ng-if, after changing it to ng-if make sure 1st point is implemented. <div ng-show="showGrids"> <pm-kendo-grid></pm-kendo-grid> <pm-dev-express-grid></pm-dev-express-grid> <pm-ig-grid></pm-ig-grid> <div> Another html content </div> <div> 6. ng-if vs ng-show
  • 18. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org • Generally most of the people follow MVC folder structure while organising angular code. 7. Folder Structure
  • 19. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org • Per convention do follow feature wise folder structure • It would make you one step ahead for angular 2 migration. 7. Folder Structure ctd.
  • 20. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org • First lets see what is dependency injection There are 3 types of DI Annotation 1. Inline Array Annotation 2. $inject property Annotation 3. Implicit Annotation 8. Follow Dependency Injection
  • 21. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org 1. Inline array annotation Here we 1st create an array with dependency we inject dependencies in string & then use the same in function function myController($scope, myService) { //Awesome controller code here } someModule.controller('myController', ['$scope', 'myService', MyController]); function myService($log) { //Awesome service code here } someModule.service('myService', ['$log', myService]); 8.1 Follow Dependency Injection ctd.
  • 22. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org 2. $inject Property annotation Here we 1st create an array with dependency we inject dependencies in string & then use the same in function function myController($scope, myService) { //Awesome controller code here } myController.$inject = ['$scope', 'myService']; someModule.controller('myController', myController); function myService($log) { //Awesome service code here } myService.$inject = ['$log']; someModule.service('myService', myService); 8.2 Follow Dependency Injection ctd.
  • 23. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org 3. Implicit annotation Here we 1st create an array with dependency we inject dependencies in string & then use the same in function function myController($scope, myService) { //Awesome controller code here } someModule.controller('myController', myController); function myService($log) { //Awesome service code here } someModule.service('myService', myService); 8.3 Follow Dependency Injection ctd.
  • 24. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org “Developer do use more simplest thing” function myController($scope, myService) { //Awesome controller code here } someModule.controller('myController', myController); But what happens is when you minify such files to reduce number of roundtrip to server, this DI technique messed up minification. function myController(a,b){};someModule.controller('myController', myController); • You can see that minified file has changed the dependency name in function. from `$scope, myService` to `a,b`. This where error will appear on the page `aProvider is missing`. • Thus you should use Array inline annotation when injecting dependency. 8. Follow Dependency Injection ctd.
  • 25. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org • Angular has built in small version of jQuery aka “jQLite” • Try to avoid use of jQuery, as it seems to be less performant • Whenever you are trying use any jQuery plugin wrap it inside a directive link function, because it provides a controller over DOM before & after element compilation by Angular 9. Utilization of jQuery
  • 26. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org • Don’t write a custom code for validation purpose, like most of the developer check each property value inside DOM. You can utilize validation feature provided by angular out of the box • Some validation property • $pristine (ng-pristine) • $error • $dirty (ng-dirty) • $submitted (ng-submitted) • $valid (ng-valid) • $invalid (ng-invalid) I’d highly recommend to look into form API from angular docs 10. Try to utilize form validation
  • 27. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org • Watcher gets evaluated its expression of each digest cycle. • Watcher count more than 2000 on page can leads to performance impact on the page. • Even data binding ({{myData}}) on the page considered as watcher $scope.$watch('myVariable', function(newValue, oldValue) { console.log('newValue ' + newValue); console.log('oldValue ' + oldValue); }, true); • Watcher has been deprecated from angular 2, so you shouldn’t be writing watcher going forward. • You can use alternative way instead of watcher. • As per new syntax you can use $doCheck lifecycle hook of component. • You can follow event $broadcast & $emit to communicate with other controller/component • You could us $viewChangesListner of ngModel controller to fire desired method (by requiring `ngModel` directive in `require` option) • You could also take an use of $parser & $formatters on ngModel (by requiring `ngModel` directive in `require` option) 11. Avoid usage of watcher
  • 28. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org • Angular used q library to use promise pattern. • Generally what people do is while making an API call the to create a custom defer & resolve it by there own like below function getData() { var deferred = $q.defer(); $http.get(url) .then(function(response) { //console.log(response.data); deferred.resolve(resolve.data); //resolve promise }, function(error) { deferred.reject(resolve.data); //reject promise }) return deferred.promise; } getData().then(function(data){ console.log(data); }, function(error){ console.log(error); }) 12. Avoid deferred antipattern.
  • 29. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org • When making an ajax we do use $http in Angular • $http all methods returns promise internally, you don’t need to create explicit promise yourself. • Previous code can be minimize function getData() { return $http.get(url); //utilized promise return by angular $http API } getData().then(function(data){ console.log(data); }, function(error){ console.log(error); }) • Likewise other library $resource, Restangular, etc. do the same thing. They return promise when it makes an ajax call. 12. Avoid deferred antipattern.
  • 32. JS JavaScripters www.javascripters.org JS JavaScripters www.javascripters.org Registers for upcoming events 3 2 1.Developing JavaScript Code for efficiency 2.Immutable and Functional JavaScript 3.Introduction of Design thinking for front-end Engineers 4.React JS with Material design 5.Introduction to Angular 2.x 6.Practice with TypeSpcript 7.Introduction to ES6 8.Automated javascript workflow with Gulp 9.NodeJs practice session 1. Total (3) online webinar under planning