AngularJS

Bootcamp

Created by Tom Wilson / @twilson63

Introductions

  • Your Name
  • Expectation of the class
  • Favorite Programming Language

About Me

  • @twilson63
  • Less is more
  • <3 the Web
  • <3 Coding
  • <3 Javascript

About the Mac

  • App Menu is at the top of the screen
  • Wifi settings are on the top right
  • Instead of Ctrl use Command
  • Command-Tab switches apps

Agenda

  • What is AngularJS?
  • Using Directives
  • Using Filters
  • Controllers and Scopes
  • More Filters
  • Using Services
  • Modules
  • Form Directives
  • Creating Directives
  • Unit Testing
  • End to End Testing

What is AngularJS?

Open Source JavaScript Framework

HTML Enhanced for Web Apps

extends HTML vocabulary for your application

Using Directives

A directive is how AngularJS extends HTML


<html ng-app>
  ...
</html>
            

A directive can be a html attribute


<tabs>
  <pane title="Tab1">....</pane>
  <pane title="Tab2">....</pane>
</tabs>
            

A directive can be a html element


<div class="ng-init: foo='bar'"></div>
<div ng-bind="foo"></div>
            

A directive can be a html class

BootStrap Directive


<html ng-app>
  <body>
    <div ng-init="name='Hello World'"></div>
    <h2>{{name}}</h2>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>
  </body>
</html>
            
Example

Bind Directive


<html ng-app>
  <body>
    <div ng-init="name='Hello World'"></div>
    <h2>{{name}}</h2>
    <div ng-bind="name"></div>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>
  </body>
</html>
            
Example

Model Directive


<html ng-app>
  <body>
    <input ng-model="name"></input>
    <h2>{{name}}</h2>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>
  </body>
</html>
            
Example

REPEAT Directive


<html ng-app>
  <body>
    <div ng-init="items=[1,2,3,4]"></div>
    <div ng-repeat="item in items">
      {{item}}
    </div>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>
  </body>
</html>            
            
Example

Click Directive


<html ng-app>
  <body>
    <div ng-init="items=[1,2,3,4]"></div>
    <input placeholder="enter number" ng-model="anumber">
    <button ng-click="items.push(anumber);anumber=''">add</button>
    <div ng-repeat="item in items">
      {{item}}
    </div>
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.11/angular.min.js"></script>

  </body>
</html>  
Example

Exercise

Use the plunker template to create an app that appends user entered colors to a list of colors.

Template

Using Filters

JSON Filter


<div ng-init="foo={ text: 'foo' }"></div>
{{foo | json }}
            
Example

CASE Filters


<div ng-init="name='bob'"></div>
{{name | uppercase }}
{{name | lowercase }}
            
Example

Date/Currency Filters


<div ng-init="money=1"></div>
<div ng-init="today='2014-02-07'"></div>
<div>{{money | currency}}</div>
<div>{{today | date:'fullDate'}}</div>
            
Example

Controllers and Scope

Lets build a Todo App

Using Angular Controllers, we are able to map a section of html to a AngularJS Scope


<div ng-controller="MainCtrl">
  ...
</div>
<script>
  function MainCtrl($scope) {
    
  }
</script>
            

Step 1: Add Items to List

Template
Answer

Step 2: Complete Task

Strikethrough the task when marked completed

Template
Answer

Remove Completed

Template
Answer

List Filters

Order By Filter


<li ng-repeat="item in items | orderBy:{exp}"></li>
            

Sort Random list of names

Template
Answer

Bonus

Sort List in descending order

Answer

Filter Filter


<li ng-repeat="item in items | filter:{exp}"></li>
            

Filter a list of Random Names

Limit To Filter


<li ng-repeat="item in items | limitTo:3">
            
Template

Using Services

Dependency Injection

DI puts the AngularJS Framework to work for you.

DI goes and gets the services you request so that your controllers are clearly defined and testable.

Injector

The injector is a service locator. There is a single injector per Angular application. The injector provides a way to look up an object instance by its name.


Diagram is from AngularJs.org

$http


function MainCtrl($scope, $http) {
  $http.get('foo.json')
    .then(function(res) {
      $scope.items = res.data;
    }, function(err) {
      alert(err.message);
    });
}
            
Example

Modules

Application Module


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

Calling the module method, with two parameters, initializes the module.


  var app = angular.module('App');
            

Calling the module method, with one parameter, returns the named module.

Including Modules


  angular.module('App', ['ngRoute']);
            

In the second parameter you can include an array of modules you would like to add to your app module.

Application Structure

Basic

Routing


  angular.module('App', ['ngRoute'])
    .config(function($routeProvider) {
      $routeProvider
        .when('/', {})
        .when('/new', {})
        .when('/:id', {});
    });
            
Routing Example

Exercise

Build A Simple Link Service CRUD Style

Forms and Directives

Forms

See the Pen vdKpA by Tom Wilson (@twilson63) on CodePen

CSS Classes

To allow styling of form as well as controls, ngModel add these CSS classes:

  • ng-valid
  • ng-invalid
  • ng-pristine
  • ng-dirty
  • The following example uses the CSS to display validity of each form control. In the example both user.name and user.email are required, but are rendered with red background only when they are dirty. This ensures that the user is not distracted with an error until after interacting with the control, and failing to satisfy its validity.

See the Pen FEwLD by Tom Wilson (@twilson63) on CodePen

Binding

A form is an instance of FormController. The form instance can optionally be published into the scope using the name attribute. Similarly, control is an instance of NgModelController. The control instance can similarly be published into the form instance using the name attribute. This implies that the internal state of both the form and the control is available for binding in the view using the standard binding primitives.

See the Pen ibGIe by Tom Wilson (@twilson63) on CodePen

Custom Validation

Angular provides basic implementation for most common html5 input types: (text, number, url, email, radio, checkbox), as well as some directives for validation (required, pattern, minlength, maxlength, min, max).

Defining your own validator can be done by defining your own directive which adds a custom validation function to the ngModel controller.

See the Pen fCurb by Tom Wilson (@twilson63) on CodePen

Custom Form Control

See the Pen DkorI by Tom Wilson (@twilson63) on CodePen

Custom Directives

Directive Definition Object

Execution

  • Compile
  • Link

restrict

String of subset of EACM which restricts the directive to a specific directive declaration style. If omitted, the default (attributes only) is used.


E - Element name: <my-directive></my-directive>
A - Attribute (default): <div my-directive="exp"> </div>
C - Class: <div class="my-directive: exp;"></div>
M - Comment: <!-- directive: my-directive exp --></p>

            

replace

if set to true then the template will replace the current element, rather than append the template to the element.

transclude

compile the content of the element and make it available to the directive. Typically used with ngTransclude. The advantage of transclusion is that the linking function receives a transclusion function which is pre-bound to the correct scope.

Demo

See the Pen tkfjC by Tom Wilson (@twilson63) on CodePen

Testing

  • Setup
  • Controllers
  • Filters
  • Directives

Setup

Karma-runner

npm install karma -g
karma init
            

Setup - using Grunt


npm install grunt-karma --save-dev
# open GruntFile
# add tasks
grunt.loadNpmTasks('grunt-karma');
# add Config
karma: {
  unit: {
    options: {
      framework: ['jasmine'],
      files: ['test/**/*.js'],
      runnerPort: 9999,
      singleRun: true,
      browsers: ['PhantomJS']
    }
  }
}
          

Controllers

See the Pen tqegm by Tom Wilson (@twilson63) on CodePen

Filters

See the Pen DGgte by Tom Wilson (@twilson63) on CodePen

Directives

Plnkr Example
Example from https://github.com/blesh
Exercise

End to End Testing

Protractor

Github

Scope

Scope

See the Pen IhDlw by Tom Wilson (@twilson63) on CodePen

Scope


Diagram is from AngularJs.org

Emitting Events

  • $on
  • $broadcast
  • $emit

$apply

$apply() is used to execute an expression in angular from outside of the angular framework. (For example from browser DOM events, setTimeout, XHR or third party libraries). Because we are calling into the angular framework we need to perform proper scope life cycle of exception handling, executing watches.

$watch

Registers a listener callback to be executed whenever the watchExpression changes.

$eval

Executes the expression on the current scope and returns the result. Any exceptions in the expression are propagated (uncaught). This is useful when evaluating Angular expressions.

Model and View

Model


Diagram is from AngularJs.org

View


Diagram is from AngularJs.org

HTML Templates

Angular is different, since its template system works on DOM objects not on strings. The template is still written in an HTML string, but it is HTML (not HTML with template sprinkled in.) The browser parses the HTML into the DOM, and the DOM becomes the input to the template engine known as the compiler. The compiler looks for directives which in turn set up watches on the model. The result is a continuously updating view which does not need template model re-merging. Your model becomes the single source-of-truth for your view.

See the Pen yGfEi by Tom Wilson (@twilson63) on CodePen

Expressions

See the Pen mdgIo by Tom Wilson (@twilson63) on CodePen

See the Pen fxIAG by Tom Wilson (@twilson63) on CodePen

jqlite and angular.element

http://docs.angularjs.org/api/angular.element

Animations

  • ngAnimate Module

ngRepeat

See the Pen zGgxH by Tom Wilson (@twilson63) on CodePen

ngView

See the Pen EeLxg by Tom Wilson (@twilson63) on CodePen

Animate.css

http://daneden.me/animate/

ngClass

See the Pen qjCEs by Tom Wilson (@twilson63) on CodePen

Custom Directive

See the Pen rfwCv by Tom Wilson (@twilson63) on CodePen

Bootstrap UI

http://angular-ui.github.io/bootstrap/

Touch


<script src="angular-touch.js"></script>
            

See the Pen wdenC by Tom Wilson (@twilson63) on CodePen

ToDo App

http://twilson63.github.io/ngTodoPouch/

Lab

Todo List - List Headlines

Create Todo - Create New Headline

Mark Complete - Vote Up/Down Headline

Delete Todo - Delete Headline

Sort Todos - Sort Headlines

Survey

Click Here