javascripters event oct 22, 2016 · 2:00 pm: common mistakes made by angular developers

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.javascrip ters.org Email: [email protected] Twitter: @javascripters_

Upload: javasscripters-community

Post on 13-Apr-2017

17 views

Category:

Software


3 download

TRANSCRIPT

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.javascripters.org

Welcome to

JavaScripters Community for Connect, Learn, Share & Explore your knowledge base

http://www.javascripters.org

Email: [email protected]

Twitter: @javascripters_

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.javascripters.org

2

About JavaScriptersJavaScripters 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 GroupsMeetup Groups JavaScriptes PuneJs HTML5-Web-Mobile-Development-Meetup Pune-UX-UI-Engineers WebF

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.javascripters.org

List of upcoming events

3

1.Developing JavaScript Code for efficiency2.Immutable and Functional JavaScript 3.Introduction of Design thinking for front-end Engineers4.React JS with Material design5.Introduction to Angular 2.x6.Practice with TypeSpcript7.Introduction to ES68.Automated javascript workflow with Gulp9.NodeJs practice session

10. Total (3) online webinar under planning

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.javascripters.org

Our Sponsor

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.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

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.javascripters.org

Mention twitter handle• @javascripters_• @pankajparkar• @angularjsWith #meetup #pune #angular #javascript tag.

Let’s have #tweet

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.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.

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.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

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.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

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.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..

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.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

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.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.

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.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.

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.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

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.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.

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.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

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.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

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.javascripters.org

• Generally most of the people follow MVC folder structure while organising angular code.

7. Folder Structure

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.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.

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.javascripters.org

• First lets see what is dependency injection

There are 3 types of DI Annotation1. Inline Array Annotation2. $inject property Annotation3. Implicit Annotation

8. Follow Dependency Injection

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.javascripters.org

1. Inline array annotationHere 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.

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.javascripters.org

2. $inject Property annotationHere 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.

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.javascripters.org

3. Implicit annotationHere 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.

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.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.

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.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

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.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

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.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

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.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.

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.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.

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.javascripters.org

Thank You

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.javascripters.org

Question & Answer

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

JS

Java

Scri

pter

swww.javascripters.org

JS

Java

Scri

pter

swww.javascripters.org

Registers for upcoming events

32

1.Developing JavaScript Code for efficiency2.Immutable and Functional JavaScript 3.Introduction of Design thinking for front-end Engineers4.React JS with Material design5.Introduction to Angular 2.x6.Practice with TypeSpcript7.Introduction to ES68.Automated javascript workflow with Gulp9.NodeJs practice session

10. Total (3) online webinar under planning