Transcript

Beginning AngularJS25 & 26 July 2015, Cowork South Bay day one

Troy Miles

Over 35 years of programming experience

Blog: http://therockncoder.blogspot.com/

Twitter: @therockncoder

Email: [email protected]

GitHub: https://github.com/Rockncoder

Agenda Day One

AngularJS

Tools

To Do App

Testing

Animation

Services/Modules

Controller As

Filters

Agenda Day Two

Deployment

Providers

Contacts App

$http & Promises

$resource

Testing ajax calls

Firebase

Custom Directives

Wrap-up

Lab #1 - Setup Check

In the labs directory

Launch the hello.html web page

You should see a greeting displayed

Lab Solution

Browser expect web applications to be delivered via a web server

While most browser will allow a web page to run from a file, most won’t allow it to access other files

If your machine is setup correctly, you will see a greeting

Lab #2 - jQuery BindingFrom the labs folder open the binding.html file

Write JavaScript to transfer the text contents of the input tag with the id of firstName, to the span with the id of showName

The code should be interactive and update as the user types

Write you code in the empty script tag near the end of the page

jQuery is already included on the page

jQuery Example<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8"> <title>Binding</title> <script src="../lib/jquery-1.10.2.min.js"></script></head><body> <label for="firstName">Enter Your Name:</label> <input type="text" id="firstName"/> <h2>Display Your Name Below</h2> <label for="showName">Show Your Name:</label> <span id="showName"></span> <script> $( document ).ready( function(){ $('#firstName').on("keyup", function(){ $('#showName').text(this.value); }); }); </script></body></html>

What’s Wrong with jQuery

jQuery is a very popular library

It is used on 50% of all web sites

It is a library not a framework

It is difficult code to test

It can lead to the creation of spaghetti code

Strict Mode

Strict mode allows you to opt in to a more restrictive version of JavaScript

Things usually permitted in JS become errors

Can be applied to an entire script or individual functions

Strict mode is a JavaScript best practice

Invoking Strict Mode

Before any other statements place the following statement

"use strict"; or 'use strict’;

Works on both the script and function level

Be careful of mixing strict and non-strict mode files

Why Use a Framework?

Leverage the work of others

More thoroughly tested

Features not plumbing

Documentation

JavaScript MV* Frameworks

Backbone.js

Knockout

EmberJS

Other frameworks & ToDoMVC

Backbone.jsCreated by Jeremy Ashkenas in 2010

19 kb production version (minimized, not gzipped)

One dependency - Underscore.js, optional jQuery

Three core concepts: models, collections, & views

Uses lots of custom events

KnockoutCreated by Steve Sanderson in 2010

47 kb production version (minimized, not gzipped)

Uses MVVM pattern

Two way data-binding

No dependencies

Supports all mainstream browsers

EmberCreated by Yehuda Katz and Tom Dale in 2011

Convention over configuration

Ember Data, a separate package, handles RESTful data

Handlebars.js, a separate package, handles templates

337 kb production version (minimized, not gzipped)

AngularJSCreated by Miško Hevery and Adam Abrons in 2009

JavaScript MVC

106 kb production version (minimized, not gzipped)

Declarative programming for UI

Imperative programming for business logic

AngularJS Key Features

Two Way Data-binding

Model View Controller

Dependency Injection

Deep Linking

HTML Templates

Directives

Testability

Two Way Data-binding

In AngularJS, binding is built into the framework

Replaces text content of HTML element with the value of the expression

{{ expression }}

<ANY ng-bind=“expression”>…</ANY>

<ANY class=“ng-bind: expression;”>…</ANY>

Model View Controller

Uses MVC or MVVM or MV* depends on who you ask

The goal is clear separation of concerns

The model is only concerned with data

The view presents the data to the user

The controller applies the business logic

Dependency InjectionA software design pattern that implements inversion of control and allows a program design to follow the dependency inversion principle

Allows a dependency to be passed to an object

Allows code to clearly state dependencies

Leads to code which is easier to debug and test

Makes it possible to minimize apps without breaking them

Deep Linking

One feature that web sites have over desktop apps are bookmarks

Deep linking allows AngularJS to restore state based on a URL

Application can use hyperlinks to navigate users around

HTML Templates

There are a lot of templating libraries

AngularJS instead uses HTML for its templates

AngularJS templates can pass HTML validators

Designers will feel at home

Easy to learn

Testability

AngularJS was engineered with testing in mind

It supports both unit and integration tests

For unit tests it works well with Jasmine

Karma is the test runner

AngularJS Example<!DOCTYPE html><html ng-app><head lang="en"> <meta charset="UTF-8"> <title>NG-Binding</title> <script src="../lib/angular.min.js"></script></head><body> <label>Enter Your Name:</label> <input type="text" ng-model="firstName"/> <h2>Display Your Name Below</h2> <label>Show Your Name:</label> <span>{{firstName}}</span> <script> </script></body></html>

ng-model

Binds an input, select, textarea to a property on the $scope

Provides validation behavior

Sets related CSS classes on the element

Lab #3 - Greet-o-matic

Open the greet-o-matic.html file

Make the page functional

The user should be able to enter their name in either input tag and have it reflect in the other and in the span tag

You shouldn’t need to write any JavaScript

Greet-o-matic Solution<!DOCTYPE html><html ng-app><head lang="en"> <meta charset="UTF-8"> <title>Greet-o-matic</title> <link rel="stylesheet" href="../css/bootstrap.css"/> <script type="text/javascript" src="../libs/angular.js"></script></head><body><div class="container" > <h1>Greet-o-matic</h1> <div class="col-lg-6"> <input type="text" ng-model="userName" placeholder="Enter name here"/> </div> <div class="col-lg-6"> <input type="text" ng-model="userName" placeholder="or over here"/> </div> <hr/> <p>Hello <span>{{userName}}</span>,<br/>Have a nice day!</p></div></body></html>

AngularJS Components

Module

Views/Controllers

Services

Directives

Module

A container for parts of your app

Allows flexibility

Unit test only need to load relevant modules

View/Controller

View

Standard HTML with angular directives and filters

Controller

Sets up the initial state of the view via $scope

Adds behavior to the view via $scope

Services

“Substitutable objects that are wired together using dependency injection (DI)”

Used to share code across an app

Lazily instantiated

Singletons

Directives

Possibly the best thing in AngularJS

Directives extend the capabilities of HTML

Merge the declarative nature of HTML to the imperative nature of JavaScript

AngularJS Directives

ng-app

ng-controller

ng-model

ng-bind

ng-repeat

ng-if

ng-switch

ng-include

ng-view

ng-src / ng-href

ng-bind vs ng-modelng-bind is one way data binding, aka output

ng-bind renders a property on scope

ng-bind has a shortcut {{}}

ng-bind is preferred over shortcut

ng-model is for two-way data binding

ng-model is intended for form elements

<input ng-model='userName' />

Name ManglingThere are basic incompatibilities between names used in HTML and those in JavaScript

HTML permits dashes and colons, JavaScript does not

To convert to JavaScript

delete any initial x-, data-

First letters after are capitalized

delete dashes, underscores, and colons

Name Mangling

So all of the following attributes equal timePicker:

data-time-picker

x:time-picker

time_picker

$scopeAn object which refers to the application model

The glue between the controller and the view

The execution context for expressions

Provides APIs

$watch - observes model

$apply - propagates model changes to AngularJS

Code Along #1- Todo App

A Todo app is the hello world app of JavaScript MVC frameworks

It shows how to create an app which creates, reads, updates, and deletes data (CRUD)

Let’s build one together

Code Along - Todo App Steps

add ng-app with module name ‘ToDo’

create angular module

create todo controller

create todos array

create add method

create delete method

create complete method

add markup

add functionality to methods

clear text box

Jasmine

Latest version 2.2, but we will be using 2.0.2

The default unit tester for AngularJS

Others will also work

Behavior Driven Development (BDD) approach

Describe - test suite

Describe is a global jasmine function

Two params

string - name of the test suite

function - implementation of the suite

Can be nested

it - specs

it is a global jasmine function

Looks like describe

A spec contains one or more expectations

If all expectations true, it is a passing spec

If any expectation fails, it is a failing spec

Expectations

Expect function

One param

The actual

Chained to a Matcher function

Matchers

Take the output of the expect function and compare it to something

Implement a boolean compare between actual value and expected

Reports to Jasmine if the expectation is true or false

Any matcher can be negated with a not before it

Some matchers

toBe - compares using ===

toEqual - works for literal variables and objects

toMatch - for regular expressions

toBeDefined - compares against 'undefined'

toBeUndefined - also compares against ‘undefined'

Some matchers (CONTINUE)

toBeNull - compares against null

toBeTruthy - truthy boolean casting

toBeFalsy - falsy boolean casting

toContain - finds an item in array

Some matchers (CONTINUE)

toBeLessThan

toBeGreaterThan

toBeCloseTo - precision math comparison

toThrow - should throw an exception

beforeEach / afterEachAre setup and teardown functions

called before and after each spec it

this

beforeEach, it, and afterEach share the same this

it is cleared before call spec call

any beforeEach not included in a describe block is executed before any Jasmine test

can use this to add custom matchers

Disabling suites and specs

prepend an 'x' before describe or it

specs inside a disabled suite are not ran

Unit Testing 3As

Arrange - Set up object to be tested

Act - Act on the object

Assert - Test the state of the object

Code Along #2 - Unit Test

Let’s add a few unit tests to our app.

We will test to make sure we can add tasks

Lab #4 - Delete Task Test

Add a unit test for the delete task

Use what you know already know based on the add task unit test

Filters

Understanding Filters

A tour of built-in filters

Building custom Filters

Lab

Understanding FiltersUsed to format data displayed to user

Strictly front-end, doesn’t change model data

Accessible using declarative or imperative syntax

{{ expression [| filter_name[:parameter_value] ... ] }}

$scope.originalText = 'hello';$scope.filteredText = $filter('uppercase')($scope.originalText);

A tour of built-in filterscurrency

date

json

lowercase

uppercase

number

filter

limitTo

orderBy

Lab #5 - Uppercase filter

Modify the ToDo app to show all tasks in uppercase only

Code Along # 4 - Capitalization

Let’s write a custom filter which will capitalize the first letter in word of a sentence

Building custom filterstempApp.filter('minimum', [function () { return function (arrTemp, minimum) { var filteredArray = []; var min = minimum ? minimum : 15; angular.forEach(arrTemp, function (value, key) { if (value.temp >= min) filteredArray.push(value); }); return filteredArray; }; }]);

Animation

ngAnimate module provides CSS and JS based animation

Some directives are animation aware

Local Storage

Current we have no way to persist the ToDo tasks

Tomorrow we will learn about Firebase, but to do we will use the local storage library

Summary

Quick History + Big Picture

ToDo App

Jasmine

Filters

Animation

TomorrowProviders

Firebase

Contacts App

Form Validation

Custom Directives

Angular 2.0


Recommended