AngularJS Introduction (Talk on Aug 5)
-
date post
21-Oct-2014 -
Category
Technology
-
view
2.279 -
download
0
description
Transcript of AngularJS Introduction (Talk on Aug 5)
AngularJSA better way to create web apps
AgendaO Introduction to AngularJSO Some concepts used in AngularJSO Testing application built with
AngularO Productivity and debugging toolsO Code organization for large projectsO Code demo as we go on
Why AngularJSO HTML was created to transmit
markup data on web. E.g. <b> tags for making text bold etc.
O JavaScript added for interactivity.O And then comes AJAX and rich web
apps.O And things get messed up by adding
listeners after getting ids, callbacks and series of callbacks.
What can AngularJS doO Less boilerplate code, faster
development with less code and thus less tests and bugs.
O Clean separation of DOM manipulation, business logic and views make things easier to test.
O Declarative UI design means designers can focus on their work without even knowing JavaScript.
O Support for cool stuff like promises.
Angular componentsThis is the real stuff
Angular App
Modules
Models
Controllers
Templates (and Views)
Directives
Services
Filters
Routes
ModuleO Angular apps have nothing like a main methodO Directive ng-app used to bootstrap the moduleO E.g. <html ng-app=“someModule”>O A module can contain several other
componentsO var module = angular.module(‘someModule’,
[])O Second argument is an array of other modules
which are requisites for the current module.
ModelsO In Angular, model is any data that is
reachable as property of $scope objectO Can also create models inside templates
using the ng-model directive e.g. <input type=“email” ng-model=“user.email”>
O Can watch models for changes using $watch(watchFn, watchAction, deepWatch)O deepWatch is a boolean which allows to
watch attributes of the object returned by watchFn
ControllersO Set up the $scopeO Add behavior to $scopeO All business logic to be written in
here.O Can use the one controller per
template to create really traditional websites.
TemplatesO Specify how things should show up
and what happens on particular user actions.
O Angular templates are not the view in MVC. Compiled angular templates are the views.
O Declaratively create the UI using directives.
DirectivesO One of the most important part of
AngularO Allows you to extend HTML to define
custom tags, attributes and classes for UI components.Jquery UI Angular Directives
<div id=“tabs”> <ul> <li><a href=“#tabs-1”> Tab1</a></li> <li><a href=“#tabs-2”> Tab2</a></li> </ul> <div id=“#tabs-1>Content</div> <div id=“#tabs-2>Content2</div></div><script>$(function() { $(‘#tabs”).tabs();});</script>
<tab-set> <tab title=“Tab1”>Content</tab> <tab title=“Tab2”>Content2</tab></tab-set>
Now what if you need tabs on 10 pages in your whole application ?
ServicesO Stuff required at various places e.g.
by various controllers.O E.g. a http request to get list of blog
posts in a blogging application would be required while showing all blog posts, in the admin edit/publish view etc.
O Three different ways to create services i.e. services, factory and provider.
FiltersO Filters are transformations applies to
objectsO Not important to logic used to
process models e.g. currency sign (like $)
O E.g. lowerCase, sort etc.O Built-in filters like jsonO Custom filters can be defined with
app.filter(‘filterName’, function (obj) {})
RoutesO Used to map templates and
associated controller to URLs.O Supports HTML5 mode where you
get history support.O That’s it !
Form ValidationO Provides special support for two
properties $valid, $invalid.O Can use them like <button ng-
disabled=“!formName.$valid”> to disable a form until its all elements are correct.
O polyfills for things like ‘required’ on non-HTML browsers
Server-side communication
O $http wraps the XHR to provide asynchronous requests.
O $resource for interacting with RESTful resources. (provided as a separate module in angular-resource.js)
O $http requests support promises (talk about this later)
Secrets of all the magic in Angular
What actually happensO Template loads with all the angular directivesO Angular script loads and after template
loading finishes, it looks for ng-app to find application boundaries.
O Compile phase – Angular walks the DOM to identify registered directive and transforms them.
O Link Phase – This runs a link function for each directive which typically creates listeners on DOM or model and keeps view and model in sync .
$scopeO $scope allows binding and
communication between controller and templates.
O All the model objects are stored on it.
O Makes sense not to store everything on it as it would degrade performance.
Data bindingO Binding two sources together and
keep then updated of changes.O Angular supports two-way data
binding.O Change in models get reflected
everywhere in view.O Changes in view gets reflected in
the model.
Dependency InjectionO Follows Law of Demeter or principle
of least knowledge.O Instead of creating things, just ask
for what is required.O E.g. to create a Car you need an
engine so instead of calling an engine Factory in the constructor, pass an engine as parameter.
O Makes things easier to test (e.g. mock $http), less code and easier to change later.
PromisesO A promise is an interface that deals
with objects that are returned or get filled in at a future point in time.
O Current approach with callbacks has problems of indentation while chaining multiple calls, losing errors reported between callbacks unless manually handled and doing real stuff in innermost callback.
PromisesO In angular a promise gives with a then
function which takes two functions as a parameter for promises getting resolved (success) or rejected (failure)
O A promise can be –O chained so you do not get code with callbacks
inside callbacks that flows out of the screen.O errors propagate and can be handled at the
end. O Assurance that previous call finishes before
next call.
Testing apps built with Angular
Why Test ?O Things do what they are expected to
do.O Future addition of code does not
affect previous features.O Reduces effort in the long run but
maybe pain to write initially.
Unit tests in AngularO Test stuffs like controllers, filters,
services and directives.O Separation of DOM code makes
testing easier and possible.O Using Jasmine like syntax and
Jasmine Spy instead of real browser.
KarmaO Karma is a test runner in JavaScriptO Test on real devicesO Control the whole workflow from
command line.O Lightening fast !!
Scenario testsO End to end tests involving complete
feature.O E.g. first page of a blog should
display N blog posts.O Done using Karma in Angular
Tools for productivity
Yeoman \m/O Lightning-fast scaffoldingO Built-in preview serverO Integrated package managementO An awesome build processO Unit testing using PhantomJS
BatarangO Chrome extension for angularO Provides performance metrics, see
scopes and values of properties in them.
O Can change the values and see the change in realtime.
IDE pluginsO Webstorm plugin is awesome.O Sublime text angular plugin.
Angular FutureO AnimationsO Breaking down into componentsO alternative syntax work without the
$scope thing but not really useful.O Much More…
Best practicesBecause you can still write yucky code in
Angular
No DOM manipulation in controller
Things which are to be used in multiple
controllers ? Use services
To wrap third party plugins like JQuery date-picker, use
directives
Write tests.This one is for me
Use promises, they are awesome.
Code organizationO Angular seed styleO Yeoman StyleO Any style you prefer
Learn more about itO Angular Channel on YoutubeO http://www.yearofmoo.comO egghead.ioO Stack OverflowO Quora