SlideShare ist ein Scribd-Unternehmen logo
1 von 32
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

Weitere ähnliche Inhalte

Was ist angesagt?

Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
Wei Ru
 
Filters in AngularJS
Filters in AngularJSFilters in AngularJS
Filters in AngularJS
Brajesh Yadav
 

Was ist angesagt? (20)

Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
 
Advanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JSAdvanced Tips & Tricks for using Angular JS
Advanced Tips & Tricks for using Angular JS
 
Different way to share data between controllers in angular js
Different way to share data between controllers in angular jsDifferent way to share data between controllers in angular js
Different way to share data between controllers in angular js
 
AngularJS in 60ish Minutes
AngularJS in 60ish MinutesAngularJS in 60ish Minutes
AngularJS in 60ish Minutes
 
Built in filters
Built in filtersBuilt in filters
Built in filters
 
AngularJs
AngularJsAngularJs
AngularJs
 
Filters in AngularJS
Filters in AngularJSFilters in AngularJS
Filters in AngularJS
 
Angularjs Basics
Angularjs BasicsAngularjs Basics
Angularjs Basics
 
Introduction to Backbone.js & Marionette.js
Introduction to Backbone.js & Marionette.jsIntroduction to Backbone.js & Marionette.js
Introduction to Backbone.js & Marionette.js
 
AngularJS Beginners Workshop
AngularJS Beginners WorkshopAngularJS Beginners Workshop
AngularJS Beginners Workshop
 
AngularJS - Overcoming performance issues. Limits.
AngularJS - Overcoming performance issues. Limits.AngularJS - Overcoming performance issues. Limits.
AngularJS - Overcoming performance issues. Limits.
 
Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing options
 
Angular JS blog tutorial
Angular JS blog tutorialAngular JS blog tutorial
Angular JS blog tutorial
 
Marionette: the Backbone framework
Marionette: the Backbone frameworkMarionette: the Backbone framework
Marionette: the Backbone framework
 
AngularJS Framework
AngularJS FrameworkAngularJS Framework
AngularJS Framework
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Angular JS - Introduction
Angular JS - IntroductionAngular JS - Introduction
Angular JS - Introduction
 
AngularJS best-practices
AngularJS best-practicesAngularJS best-practices
AngularJS best-practices
 
Building an End-to-End AngularJS Application
Building an End-to-End AngularJS ApplicationBuilding an End-to-End AngularJS Application
Building an End-to-End AngularJS Application
 
AngularJs presentation
AngularJs presentation AngularJs presentation
AngularJs presentation
 

Andere mochten auch

555858
555858555858
555858
yeeeaa
 
LAMARAN YOPIE FERDIAN 081220209669
LAMARAN YOPIE FERDIAN 081220209669LAMARAN YOPIE FERDIAN 081220209669
LAMARAN YOPIE FERDIAN 081220209669
yopie ferdian
 

Andere mochten auch (20)

JavaScripters Event on Sep 10, 2016 · 10:30 AM: Sass
JavaScripters Event on Sep 10, 2016 · 10:30 AM: SassJavaScripters Event on Sep 10, 2016 · 10:30 AM: Sass
JavaScripters Event on Sep 10, 2016 · 10:30 AM: Sass
 
JavaScripters Event Sep 17, 2016 · 2:00 PM: Scalable Javascript Design Patterns
JavaScripters Event Sep 17, 2016 · 2:00 PM: Scalable Javascript Design PatternsJavaScripters Event Sep 17, 2016 · 2:00 PM: Scalable Javascript Design Patterns
JavaScripters Event Sep 17, 2016 · 2:00 PM: Scalable Javascript Design Patterns
 
Poliedros
PoliedrosPoliedros
Poliedros
 
555858
555858555858
555858
 
El Comercio
El Comercio El Comercio
El Comercio
 
Define que es un cliente
Define que es un clienteDefine que es un cliente
Define que es un cliente
 
Grooming
GroomingGrooming
Grooming
 
Tarea del seminario 5
Tarea del seminario 5Tarea del seminario 5
Tarea del seminario 5
 
Transcript Dr. Obumneke Amadi - Health Literacy
Transcript   Dr. Obumneke Amadi - Health LiteracyTranscript   Dr. Obumneke Amadi - Health Literacy
Transcript Dr. Obumneke Amadi - Health Literacy
 
Trabajo tecnología
Trabajo tecnologíaTrabajo tecnología
Trabajo tecnología
 
profile-3p2
profile-3p2profile-3p2
profile-3p2
 
PARCIAL FINAL
PARCIAL FINAL PARCIAL FINAL
PARCIAL FINAL
 
Informe de COMUEDA, de fecha 23/05/2014 Asistencia a familias afectadas por l...
Informe de COMUEDA, de fecha 23/05/2014 Asistencia a familias afectadas por l...Informe de COMUEDA, de fecha 23/05/2014 Asistencia a familias afectadas por l...
Informe de COMUEDA, de fecha 23/05/2014 Asistencia a familias afectadas por l...
 
Copia de diferido territorial de Guatemala
Copia de diferido territorial de Guatemala Copia de diferido territorial de Guatemala
Copia de diferido territorial de Guatemala
 
SEMANA VERDE
SEMANA VERDESEMANA VERDE
SEMANA VERDE
 
Tarea del seminario 3
Tarea del seminario 3Tarea del seminario 3
Tarea del seminario 3
 
LAMARAN YOPIE FERDIAN 081220209669
LAMARAN YOPIE FERDIAN 081220209669LAMARAN YOPIE FERDIAN 081220209669
LAMARAN YOPIE FERDIAN 081220209669
 
Las Tic.
Las Tic. Las Tic.
Las Tic.
 
Símbolos patrios de perú pdf
Símbolos patrios de perú pdfSímbolos patrios de perú pdf
Símbolos patrios de perú pdf
 
Social media Applications in Medicine and Health Care
Social media Applications in Medicine and Health CareSocial media Applications in Medicine and Health Care
Social media Applications in Medicine and Health Care
 

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

AgularJS basics- angular directives and controllers
AgularJS basics- angular directives and controllersAgularJS basics- angular directives and controllers
AgularJS basics- angular directives and controllers
jobinThomas54
 

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

Basics of AngularJS
Basics of AngularJSBasics of AngularJS
Basics of AngularJS
 
Mini-Training: AngularJS
Mini-Training: AngularJSMini-Training: AngularJS
Mini-Training: AngularJS
 
Yeoman AngularJS and D3 - A solid stack for web apps
Yeoman AngularJS and D3 - A solid stack for web appsYeoman AngularJS and D3 - A solid stack for web apps
Yeoman AngularJS and D3 - A solid stack for web apps
 
Angular Seminar-js
Angular Seminar-jsAngular Seminar-js
Angular Seminar-js
 
AgularJS basics- angular directives and controllers
AgularJS basics- angular directives and controllersAgularJS basics- angular directives and controllers
AgularJS basics- angular directives and controllers
 
Angular js-crash-course
Angular js-crash-courseAngular js-crash-course
Angular js-crash-course
 
SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015SharePoint Saturday Atlanta 2015
SharePoint Saturday Atlanta 2015
 
Introduction to AngularJs
Introduction to AngularJsIntroduction to AngularJs
Introduction to AngularJs
 
Angular js
Angular jsAngular js
Angular js
 
Coffee@DBG - Exploring Angular JS
Coffee@DBG - Exploring Angular JSCoffee@DBG - Exploring Angular JS
Coffee@DBG - Exploring Angular JS
 
AngularJS Basics
AngularJS BasicsAngularJS Basics
AngularJS Basics
 
Angular Js Basics
Angular Js BasicsAngular Js Basics
Angular Js Basics
 
Building and deploying React applications
Building and deploying React applicationsBuilding and deploying React applications
Building and deploying React applications
 
AngularJS 101
AngularJS 101AngularJS 101
AngularJS 101
 
Building Isomorphic Apps (JSConf.Asia 2014)
Building Isomorphic Apps (JSConf.Asia 2014)Building Isomorphic Apps (JSConf.Asia 2014)
Building Isomorphic Apps (JSConf.Asia 2014)
 
A Story about AngularJS modularization development
A Story about AngularJS modularization developmentA Story about AngularJS modularization development
A Story about AngularJS modularization development
 
Angular 4 for Java Developers
Angular 4 for Java DevelopersAngular 4 for Java Developers
Angular 4 for Java Developers
 
Understanding angular js
Understanding angular jsUnderstanding angular js
Understanding angular js
 
Angular Mini-Challenges
Angular Mini-ChallengesAngular Mini-Challenges
Angular Mini-Challenges
 
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJSAngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
AngularJS training - Day 1 - Basics: Why, What and basic features of AngularJS
 

Kürzlich hochgeladen

introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
VishalKumarJha10
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Kürzlich hochgeladen (20)

The Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdfThe Top App Development Trends Shaping the Industry in 2024-25 .pdf
The Top App Development Trends Shaping the Industry in 2024-25 .pdf
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
ManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide DeckManageIQ - Sprint 236 Review - Slide Deck
ManageIQ - Sprint 236 Review - Slide Deck
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...Chinsurah Escorts ☎️8617697112  Starting From 5K to 15K High Profile Escorts ...
Chinsurah Escorts ☎️8617697112 Starting From 5K to 15K High Profile Escorts ...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdfAzure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
Azure_Native_Qumulo_High_Performance_Compute_Benchmarks.pdf
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 

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: pune.javascripters@gmail.com 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