SlideShare a Scribd company logo
Cleaner Opinionated AngularJS
Prabhakar Doraisamy	

August 2014
var app = angular.module('app', []);	

app.controller('MyCtrl', function () {

…

});
function MainCtrl () {

	

 …

}	

angular

.module('app', [])

.controller('MainCtrl', MainCtrl);
Better
(function () {

	

 angular.module('app', []);	

	

 function MainCtrl () {

	

 }



	

 angular

	

 .module('app')

	

 .controller('MainCtrl', MainCtrl);

})();
BestDefining a module
• aids in stack traces as functions aren't anonymous • avoids polluting the global namespace
Better
Better #2Dependency injection
• Using the array syntax to declare dependencies works with minification
function MainCtrl(anyVariableName, $q) {	

}

MainCtrl.$inject = ['$http',‘$q’];	

angular

.module('app', [])

.controller('MainCtrl', MainCtrl);
var app = angular.module('app', []);	

app.controller('MainCtrl', [ '$http', '$q', function($http, $q){

…

});
var app = angular.module('app', []);	

app.controller('MainCtrl', function ($http, $q) {

…

});
<div ng-controller="MainCtrl">	

{{ someObject }}	

</div>
<div ng-controller="MainCtrl as main">	

{{ main.someObject }}	

</div>
Better
<div>

{{ main.someObject }}

</div>	

!
function config ($routeProvider) {

$routeProvider

.when('/', {

templateUrl: 'views/main.html',

controller: 'MainCtrl',

controllerAs: 'main'

});

}	

angular

.module('app')

.config(config);
BestAdding controller to a view
• Controllers are classes	

• aids in nested scoping and controller instance reference.
• avoids tight coupling ie., reusable view with different controllers	

• avoids using $parent to access any parent controllers from a child controller
function MainCtrl ($scope) {

$scope.someObject = {};

$scope.doSomething = function () {

};

}	

angular

.module('app')

.controller('MainCtrl', MainCtrl);
function MainCtrl ($scope) {

this.someObject = {};

this._$scope = $scope;

}	

MainCtrl.prototype.doSomething = function () {

// use this._$scope

};	

angular

.module('app')

.controller('MainCtrl', MainCtrl);
Slightly better
function MainCtrl () {

this.someObject = {};

this.doSomething = function () {

};

}	

angular

.module('app')

.controller('MainCtrl', MainCtrl);	

function config ($routeProvider) {

$routeProvider

.when('/', {

templateUrl: 'views/main.html',

controller: 'MainCtrl',

controllerAs: 'main'

});

}
Betterthis and $scope
• Good for inheritance	

• controllerAs syntax uses this keyword inside controllers instead of $scope. 	

• When using controllerAs, the controller is infact bound to $scope, but there is a degree of separation.
function SomeService () {

}	

angular

.module('app')

.factory('$$SomeService', SomeService);
• $ incites they’re public and can be used.	

• $scope and $rootScope	

• $$ are considered private methods.	

• $$listeners, which are available on the Object	

function SomeService () {

}	

angular

.module('app')

.factory('SomeService', SomeService);
Better
• Avoid using two different names for the Service definition, and the function name for consistency
and stack tracing.
Naming services/directives/providers/factories
<input ng-model=“myModel">	

function MainCtrl(){

$scope.$watch('myModel', function () {

// go

});

}
<input ng-model="myModel" ng-change="callback">	

function MainCtrl(){

$scope.callback = function () {

// go

};

} 	

Better
• Avoid $scope.$watch unless there are no others options	

• less performant than binding an expression to something like ng-change
Watching data change
function MainCtrl () {

this.doSomething = function () {

};

}	

angular

.module('app')

.controller('MainCtrl', MainCtrl);
function MainCtrl (SomeService) {

this.doSomething = SomeService.doSomething;

}	

angular

.module('app')

.controller('MainCtrl', MainCtrl);
Better
• delegating logic to Factories/Services	

• maximises reusability
Controller logic
function AnotherService () {

var someValue = '';

var someMethod = function () {

};	

return {

someValue: someValue,

someMethod: someMethod

};

}	

angular

.module('app')

.factory('AnotherService',AnotherService);
function AnotherService () {

var AnotherService = {};

AnotherService.someValue = ‘’;

AnotherService.someMethod = function () {

};	

return AnotherService;

}	

angular

.module('app')

.factory('AnotherService',AnotherService);
Better
• makes internal module namespacing a little easier	

• easy to read any private methods and variables
Factory
function MainCtrl (SomeService) {

this.makeActive = function (elem) {

$(elem).addClass(‘test’);

};

}	

angular

.module('app')

.controller('MainCtrl', MainCtrl);	

function SomeDirective (SomeService) {

return {

restrict: 'EA',

template: [

'<a href="" class="myawesomebutton" ng-transclude>',

'<i class="icon-ok-sign"></i>',

'</a>'

].join(''),	

link: function ($scope, $element, $attrs) {

// DOM manipulation/events here!

$element.on('click', function () {

$(this).addClass('test');

});

}

};

}	

angular

.module('app')

.directive('SomeDirective', SomeDirective);
Better
• Any DOM manipulation should take place inside a directive, and only directives
DOM manipulation
If you are writing $(element) somewhere in your
controller, its a indication that you need a directive.
function ngFocus (SomeService) {

return {};

}	

angular

.module('app')

.directive('ngFocus', ngFocus);
function focusFire (SomeService) {

return {};

}	

angular

.module('app')

.directive('focusFire', focusFire);
Better
• Custom directives should not be ng-* prefixed to prevent future core overrides
Naming a directive
<!-- directive: my-directive -->	

<div class="my-directive"></div>
Followed by adding restrict usage using the restrict property inside each directive's Object. 	

• E for element	

• A for attribute	

• M for comment (avoid)	

• C for className (avoid this too as it's even more confusing, but plays better with IE).	

• Multiple restrictions, such as restrict: 'EA'.
BetterDirective usage restriction
<my-directive></my-directive>	

<div my-directive></div>
function MainCtrl (SomeService) {

var self = this; // unresolved

self.something;

// resolved asynchronously 

SomeService.doSomething().then(function (response) {

self.something = response;

});

}	

angular

.module('app')

.controller('MainCtrl', MainCtrl);
function config ($routeProvider) {

$routeProvider

.when('/', {

templateUrl: 'views/main.html',

resolve: {

doSomething: function (SomeService) {

return SomeService.doSomething();

}

}

});

}

function MainCtrl (SomeService) {

// resolved!

this.something = SomeService.something;

}

angular..module(‘app').controller('MainCtrl', MainCtrl);

angular.module(‘app').config(config);
Better
// config with resolve pointing to relevant controller

function config ($routeProvider) {

$routeProvider

.when('/', {

templateUrl: 'views/main.html',

controller: 'MainCtrl',

controllerAs: 'main',

resolve: MainCtrl.resolve

});

}	

// controller as usual

function MainCtrl (SomeService) {

// resolved!

this.something = SomeService.something;

}	

// create the resolved property

MainCtrl.resolve = {

doSomething: function (SomeService) {

return SomeService.doSomething();

}

};	

angular

.module(‘app')

.controller('MainCtrl', MainCtrl)

.config(config);
BestInit data for a view
• keeping router tidy	

• progress. indicator using the $routeChangeStart event
• keeping controller tidy
Ad

Recommended

AngularJs-training
AngularJs-training
Pratchaya Suputsopon
 
AngularJs
AngularJs
syam kumar kk
 
AngularJs Crash Course
AngularJs Crash Course
Keith Bloomfield
 
AngularJs $provide API internals & circular dependency problem.
AngularJs $provide API internals & circular dependency problem.
Yan Yankowski
 
Building Custom AngularJS Directives - A Step-by-Step Guide - Dan Wahlin | Fa...
Building Custom AngularJS Directives - A Step-by-Step Guide - Dan Wahlin | Fa...
FalafelSoftware
 
"Angular.js Concepts in Depth" by Aleksandar Simović
"Angular.js Concepts in Depth" by Aleksandar Simović
JS Belgrade
 
Intro to Angular.JS Directives
Intro to Angular.JS Directives
Christian Lilley
 
Custom AngularJS Directives
Custom AngularJS Directives
yprodev
 
AngularJS Internal
AngularJS Internal
Eyal Vardi
 
AngularJS Basics with Example
AngularJS Basics with Example
Sergey Bolshchikov
 
Building Robust jQuery Plugins
Building Robust jQuery Plugins
Jörn Zaefferer
 
Angular In Depth
Angular In Depth
Mindfire Solutions
 
Ultimate Introduction To AngularJS
Ultimate Introduction To AngularJS
Jacopo Nardiello
 
AngularJS $Provide Service
AngularJS $Provide Service
Eyal Vardi
 
AngularJS Directives
AngularJS Directives
Eyal Vardi
 
Angular custom directives
Angular custom directives
Alexe Bogdan
 
AngularJS Architecture
AngularJS Architecture
Eyal Vardi
 
Basics of AngularJS
Basics of AngularJS
Filip Janevski
 
AngularJS Framework
AngularJS Framework
Barcamp Saigon
 
Solid angular
Solid angular
Nir Kaufman
 
AngularJS.part1
AngularJS.part1
Andrey Kolodnitsky
 
AngularJS Basic Training
AngularJS Basic Training
Cornel Stefanache
 
ChtiJUG - Introduction à Angular2
ChtiJUG - Introduction à Angular2
Demey Emmanuel
 
Practical AngularJS
Practical AngularJS
Wei Ru
 
Technozaure - Angular2
Technozaure - Angular2
Demey Emmanuel
 
AngularJS Animations
AngularJS Animations
Eyal Vardi
 
Angular js routing options
Angular js routing options
Nir Kaufman
 
Upgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.x
Eyal Vardi
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto University
SC5.io
 
Introduction to AngularJs
Introduction to AngularJs
murtazahaveliwala
 

More Related Content

What's hot (20)

AngularJS Internal
AngularJS Internal
Eyal Vardi
 
AngularJS Basics with Example
AngularJS Basics with Example
Sergey Bolshchikov
 
Building Robust jQuery Plugins
Building Robust jQuery Plugins
Jörn Zaefferer
 
Angular In Depth
Angular In Depth
Mindfire Solutions
 
Ultimate Introduction To AngularJS
Ultimate Introduction To AngularJS
Jacopo Nardiello
 
AngularJS $Provide Service
AngularJS $Provide Service
Eyal Vardi
 
AngularJS Directives
AngularJS Directives
Eyal Vardi
 
Angular custom directives
Angular custom directives
Alexe Bogdan
 
AngularJS Architecture
AngularJS Architecture
Eyal Vardi
 
Basics of AngularJS
Basics of AngularJS
Filip Janevski
 
AngularJS Framework
AngularJS Framework
Barcamp Saigon
 
Solid angular
Solid angular
Nir Kaufman
 
AngularJS.part1
AngularJS.part1
Andrey Kolodnitsky
 
AngularJS Basic Training
AngularJS Basic Training
Cornel Stefanache
 
ChtiJUG - Introduction à Angular2
ChtiJUG - Introduction à Angular2
Demey Emmanuel
 
Practical AngularJS
Practical AngularJS
Wei Ru
 
Technozaure - Angular2
Technozaure - Angular2
Demey Emmanuel
 
AngularJS Animations
AngularJS Animations
Eyal Vardi
 
Angular js routing options
Angular js routing options
Nir Kaufman
 
Upgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.x
Eyal Vardi
 
AngularJS Internal
AngularJS Internal
Eyal Vardi
 
Building Robust jQuery Plugins
Building Robust jQuery Plugins
Jörn Zaefferer
 
Ultimate Introduction To AngularJS
Ultimate Introduction To AngularJS
Jacopo Nardiello
 
AngularJS $Provide Service
AngularJS $Provide Service
Eyal Vardi
 
AngularJS Directives
AngularJS Directives
Eyal Vardi
 
Angular custom directives
Angular custom directives
Alexe Bogdan
 
AngularJS Architecture
AngularJS Architecture
Eyal Vardi
 
ChtiJUG - Introduction à Angular2
ChtiJUG - Introduction à Angular2
Demey Emmanuel
 
Practical AngularJS
Practical AngularJS
Wei Ru
 
Technozaure - Angular2
Technozaure - Angular2
Demey Emmanuel
 
AngularJS Animations
AngularJS Animations
Eyal Vardi
 
Angular js routing options
Angular js routing options
Nir Kaufman
 
Upgrading from Angular 1.x to Angular 2.x
Upgrading from Angular 1.x to Angular 2.x
Eyal Vardi
 

Similar to Opinionated AngularJS (20)

Angular.js Primer in Aalto University
Angular.js Primer in Aalto University
SC5.io
 
Introduction to AngularJs
Introduction to AngularJs
murtazahaveliwala
 
Step by Step - AngularJS
Step by Step - AngularJS
Infragistics
 
AngularJS
AngularJS
LearningTech
 
Angular Presentation
Angular Presentation
Adam Moore
 
Angular
Angular
LearningTech
 
Angular
Angular
LearningTech
 
Angular workshop - Full Development Guide
Angular workshop - Full Development Guide
Nitin Giri
 
Intro to AngularJs
Intro to AngularJs
SolTech, Inc.
 
Introduction to AngularJS
Introduction to AngularJS
Yoann Gotthilf
 
AngularJS in practice
AngularJS in practice
Eugene Fidelin
 
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
Learnimtactics
 
angularJs Workshop
angularJs Workshop
Ran Wahle
 
A gently introduction to AngularJS
A gently introduction to AngularJS
Gregor Woiwode
 
Dive into Angular, part 1: Introduction
Dive into Angular, part 1: Introduction
Oleksii Prohonnyi
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
Ran Wahle
 
AngularJS Basics
AngularJS Basics
Ravi Mone
 
Angular basicschat
Angular basicschat
Yu Jin
 
Everything You Need To Know About AngularJS
Everything You Need To Know About AngularJS
Sina Mirhejazi
 
Angular js-crash-course
Angular js-crash-course
Keith Bloomfield
 
Angular.js Primer in Aalto University
Angular.js Primer in Aalto University
SC5.io
 
Step by Step - AngularJS
Step by Step - AngularJS
Infragistics
 
Angular Presentation
Angular Presentation
Adam Moore
 
Angular workshop - Full Development Guide
Angular workshop - Full Development Guide
Nitin Giri
 
Introduction to AngularJS
Introduction to AngularJS
Yoann Gotthilf
 
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
AngularJs Superheroic JavaScript MVW Framework Services by Miracle Studios
Learnimtactics
 
angularJs Workshop
angularJs Workshop
Ran Wahle
 
A gently introduction to AngularJS
A gently introduction to AngularJS
Gregor Woiwode
 
Dive into Angular, part 1: Introduction
Dive into Angular, part 1: Introduction
Oleksii Prohonnyi
 
AngularJs Workshop SDP December 28th 2014
AngularJs Workshop SDP December 28th 2014
Ran Wahle
 
AngularJS Basics
AngularJS Basics
Ravi Mone
 
Angular basicschat
Angular basicschat
Yu Jin
 
Everything You Need To Know About AngularJS
Everything You Need To Know About AngularJS
Sina Mirhejazi
 
Ad

Recently uploaded (20)

The basics of hydrogenation of co2 reaction
The basics of hydrogenation of co2 reaction
kumarrahul230759
 
Introduction to Natural Language Processing - Stages in NLP Pipeline, Challen...
Introduction to Natural Language Processing - Stages in NLP Pipeline, Challen...
resming1
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
20CE601- DESIGN OF STEEL STRUCTURES ,INTRODUCTION AND ALLOWABLE STRESS DESIGN
20CE601- DESIGN OF STEEL STRUCTURES ,INTRODUCTION AND ALLOWABLE STRESS DESIGN
gowthamvicky1
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
grade 9 science q1 quiz.pptx science quiz
grade 9 science q1 quiz.pptx science quiz
norfapangolima
 
Fundamentals of Digital Design_Class_12th April.pptx
Fundamentals of Digital Design_Class_12th April.pptx
drdebarshi1993
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
João Esperancinha
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
Engineering Mechanics Introduction and its Application
Engineering Mechanics Introduction and its Application
Sakthivel M
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
Low Power SI Class E Power Amplifier and Rf Switch for Health Care
Low Power SI Class E Power Amplifier and Rf Switch for Health Care
ieijjournal
 
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
ravicivil
 
The basics of hydrogenation of co2 reaction
The basics of hydrogenation of co2 reaction
kumarrahul230759
 
Introduction to Natural Language Processing - Stages in NLP Pipeline, Challen...
Introduction to Natural Language Processing - Stages in NLP Pipeline, Challen...
resming1
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-Adaptaflex.pdf
djiceramil
 
20CE601- DESIGN OF STEEL STRUCTURES ,INTRODUCTION AND ALLOWABLE STRESS DESIGN
20CE601- DESIGN OF STEEL STRUCTURES ,INTRODUCTION AND ALLOWABLE STRESS DESIGN
gowthamvicky1
 
How Binning Affects LED Performance & Consistency.pdf
How Binning Affects LED Performance & Consistency.pdf
Mina Anis
 
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
WIRELESS COMMUNICATION SECURITY AND IT’S PROTECTION METHODS
samueljackson3773
 
grade 9 science q1 quiz.pptx science quiz
grade 9 science q1 quiz.pptx science quiz
norfapangolima
 
Fundamentals of Digital Design_Class_12th April.pptx
Fundamentals of Digital Design_Class_12th April.pptx
drdebarshi1993
 
Impurities of Water and their Significance.pptx
Impurities of Water and their Significance.pptx
dhanashree78
 
Structural Design for Residential-to-Restaurant Conversion
Structural Design for Residential-to-Restaurant Conversion
DanielRoman285499
 
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
Decoding Kotlin - Your Guide to Solving the Mysterious in Kotlin - Devoxx PL ...
João Esperancinha
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
362 Alec Data Center Solutions-Slysium Data Center-AUH-Glands & Lugs, Simplex...
djiceramil
 
Engineering Mechanics Introduction and its Application
Engineering Mechanics Introduction and its Application
Sakthivel M
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
社内勉強会資料_Chain of Thought .
社内勉強会資料_Chain of Thought .
NABLAS株式会社
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Rigor, ethics, wellbeing and resilience in the ICT doctoral journey
Yannis
 
Low Power SI Class E Power Amplifier and Rf Switch for Health Care
Low Power SI Class E Power Amplifier and Rf Switch for Health Care
ieijjournal
 
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
COMPOSITE COLUMN IN STEEL CONCRETE COMPOSITES.ppt
ravicivil
 
Ad

Opinionated AngularJS

  • 2. var app = angular.module('app', []); app.controller('MyCtrl', function () {
 …
 }); function MainCtrl () {
 …
 } angular
 .module('app', [])
 .controller('MainCtrl', MainCtrl); Better (function () {
 angular.module('app', []); function MainCtrl () {
 }
 
 angular
 .module('app')
 .controller('MainCtrl', MainCtrl);
 })(); BestDefining a module • aids in stack traces as functions aren't anonymous • avoids polluting the global namespace
  • 3. Better Better #2Dependency injection • Using the array syntax to declare dependencies works with minification function MainCtrl(anyVariableName, $q) { }
 MainCtrl.$inject = ['$http',‘$q’]; angular
 .module('app', [])
 .controller('MainCtrl', MainCtrl); var app = angular.module('app', []); app.controller('MainCtrl', [ '$http', '$q', function($http, $q){
 …
 }); var app = angular.module('app', []); app.controller('MainCtrl', function ($http, $q) {
 …
 });
  • 4. <div ng-controller="MainCtrl"> {{ someObject }} </div> <div ng-controller="MainCtrl as main"> {{ main.someObject }} </div> Better <div>
 {{ main.someObject }}
 </div> ! function config ($routeProvider) {
 $routeProvider
 .when('/', {
 templateUrl: 'views/main.html',
 controller: 'MainCtrl',
 controllerAs: 'main'
 });
 } angular
 .module('app')
 .config(config); BestAdding controller to a view • Controllers are classes • aids in nested scoping and controller instance reference. • avoids tight coupling ie., reusable view with different controllers • avoids using $parent to access any parent controllers from a child controller
  • 5. function MainCtrl ($scope) {
 $scope.someObject = {};
 $scope.doSomething = function () {
 };
 } angular
 .module('app')
 .controller('MainCtrl', MainCtrl); function MainCtrl ($scope) {
 this.someObject = {};
 this._$scope = $scope;
 } MainCtrl.prototype.doSomething = function () {
 // use this._$scope
 }; angular
 .module('app')
 .controller('MainCtrl', MainCtrl); Slightly better function MainCtrl () {
 this.someObject = {};
 this.doSomething = function () {
 };
 } angular
 .module('app')
 .controller('MainCtrl', MainCtrl); function config ($routeProvider) {
 $routeProvider
 .when('/', {
 templateUrl: 'views/main.html',
 controller: 'MainCtrl',
 controllerAs: 'main'
 });
 } Betterthis and $scope • Good for inheritance • controllerAs syntax uses this keyword inside controllers instead of $scope. • When using controllerAs, the controller is infact bound to $scope, but there is a degree of separation.
  • 6. function SomeService () {
 } angular
 .module('app')
 .factory('$$SomeService', SomeService); • $ incites they’re public and can be used. • $scope and $rootScope • $$ are considered private methods. • $$listeners, which are available on the Object function SomeService () {
 } angular
 .module('app')
 .factory('SomeService', SomeService); Better • Avoid using two different names for the Service definition, and the function name for consistency and stack tracing. Naming services/directives/providers/factories
  • 7. <input ng-model=“myModel"> function MainCtrl(){
 $scope.$watch('myModel', function () {
 // go
 });
 } <input ng-model="myModel" ng-change="callback"> function MainCtrl(){
 $scope.callback = function () {
 // go
 };
 } Better • Avoid $scope.$watch unless there are no others options • less performant than binding an expression to something like ng-change Watching data change
  • 8. function MainCtrl () {
 this.doSomething = function () {
 };
 } angular
 .module('app')
 .controller('MainCtrl', MainCtrl); function MainCtrl (SomeService) {
 this.doSomething = SomeService.doSomething;
 } angular
 .module('app')
 .controller('MainCtrl', MainCtrl); Better • delegating logic to Factories/Services • maximises reusability Controller logic
  • 9. function AnotherService () {
 var someValue = '';
 var someMethod = function () {
 }; return {
 someValue: someValue,
 someMethod: someMethod
 };
 } angular
 .module('app')
 .factory('AnotherService',AnotherService); function AnotherService () {
 var AnotherService = {};
 AnotherService.someValue = ‘’;
 AnotherService.someMethod = function () {
 }; return AnotherService;
 } angular
 .module('app')
 .factory('AnotherService',AnotherService); Better • makes internal module namespacing a little easier • easy to read any private methods and variables Factory
  • 10. function MainCtrl (SomeService) {
 this.makeActive = function (elem) {
 $(elem).addClass(‘test’);
 };
 } angular
 .module('app')
 .controller('MainCtrl', MainCtrl); function SomeDirective (SomeService) {
 return {
 restrict: 'EA',
 template: [
 '<a href="" class="myawesomebutton" ng-transclude>',
 '<i class="icon-ok-sign"></i>',
 '</a>'
 ].join(''), link: function ($scope, $element, $attrs) {
 // DOM manipulation/events here!
 $element.on('click', function () {
 $(this).addClass('test');
 });
 }
 };
 } angular
 .module('app')
 .directive('SomeDirective', SomeDirective); Better • Any DOM manipulation should take place inside a directive, and only directives DOM manipulation
  • 11. If you are writing $(element) somewhere in your controller, its a indication that you need a directive.
  • 12. function ngFocus (SomeService) {
 return {};
 } angular
 .module('app')
 .directive('ngFocus', ngFocus); function focusFire (SomeService) {
 return {};
 } angular
 .module('app')
 .directive('focusFire', focusFire); Better • Custom directives should not be ng-* prefixed to prevent future core overrides Naming a directive
  • 13. <!-- directive: my-directive --> <div class="my-directive"></div> Followed by adding restrict usage using the restrict property inside each directive's Object. • E for element • A for attribute • M for comment (avoid) • C for className (avoid this too as it's even more confusing, but plays better with IE). • Multiple restrictions, such as restrict: 'EA'. BetterDirective usage restriction <my-directive></my-directive> <div my-directive></div>
  • 14. function MainCtrl (SomeService) {
 var self = this; // unresolved
 self.something;
 // resolved asynchronously 
 SomeService.doSomething().then(function (response) {
 self.something = response;
 });
 } angular
 .module('app')
 .controller('MainCtrl', MainCtrl); function config ($routeProvider) {
 $routeProvider
 .when('/', {
 templateUrl: 'views/main.html',
 resolve: {
 doSomething: function (SomeService) {
 return SomeService.doSomething();
 }
 }
 });
 }
 function MainCtrl (SomeService) {
 // resolved!
 this.something = SomeService.something;
 }
 angular..module(‘app').controller('MainCtrl', MainCtrl);
 angular.module(‘app').config(config); Better // config with resolve pointing to relevant controller
 function config ($routeProvider) {
 $routeProvider
 .when('/', {
 templateUrl: 'views/main.html',
 controller: 'MainCtrl',
 controllerAs: 'main',
 resolve: MainCtrl.resolve
 });
 } // controller as usual
 function MainCtrl (SomeService) {
 // resolved!
 this.something = SomeService.something;
 } // create the resolved property
 MainCtrl.resolve = {
 doSomething: function (SomeService) {
 return SomeService.doSomething();
 }
 }; angular
 .module(‘app')
 .controller('MainCtrl', MainCtrl)
 .config(config); BestInit data for a view • keeping router tidy • progress. indicator using the $routeChangeStart event • keeping controller tidy