96
AngularJs Intermediate

Angular Intermediate

Embed Size (px)

Citation preview

Page 1: Angular Intermediate

AngularJs Intermediate

Page 3: Angular Intermediate

Target

People who have already some experience with angular and wanted to see more feature.

Page 4: Angular Intermediate

Topics

● Integration with RESTful API● Code modularization● Client side validations● Custom directive● Testing

Page 5: Angular Intermediate

Slack - Join us on MEAN milan

If you are not there already: http://meanmilan.herokuapp.com/

https://meanmilan.slack.com/

Page 6: Angular Intermediate

Ninja time!

https://github.com/linkmesrl/ngIntermediate

Page 7: Angular Intermediate

What we are going to do

Page 8: Angular Intermediate

What is it?

Back end: Node.js + Express + MongoDb

Front end: Angular Js

Page 9: Angular Intermediate

1° Lesson

$http, $resource

Page 10: Angular Intermediate

Angular $http

Page 11: Angular Intermediate

Angular $http - shortcut

Page 12: Angular Intermediate

Angular $http - in the service

Page 13: Angular Intermediate

Angular $http - in controller

Page 14: Angular Intermediate

Ok let’s go $resource

Page 15: Angular Intermediate

$resource - Usage

$resource(url, [paramDefaults], [actions], options);

https://docs.angularjs.org/api/ngResource/service/$resource

Page 16: Angular Intermediate

$resource - Let’s create the model

Page 17: Angular Intermediate

$resource

Each of the model instances will have methods, which could be used for the different CRUD operation. In one line of code.

It’s not free! ngResource should be installed in your app

Page 18: Angular Intermediate

$resource - Default method

'get': {method:'GET'},

'save': {method:'POST'},

'query': {method:'GET', isArray:true},

'remove': {method:'DELETE'},

'delete': {method:'DELETE'}

Page 19: Angular Intermediate

$resource - How to use it - Query

// Get allvar ninjas = Ninja.query();

Page 20: Angular Intermediate

$resource - How to use it - Get

// get singleNinja.get({ id: 1}, function (ninja) {...});

// get single using $promiseNinja.get({ id: 1}).$promise.then(...);

Page 21: Angular Intermediate

$resource - Handling returned data

// $save, $remove ($delete)ninja.$save();ninja.$remove();

Page 22: Angular Intermediate

Let’s code

● Create a service to incapsulate the $resource

● Create 2 controllers to handle the requests

● Connect the views with their controllers

Page 23: Angular Intermediate

$resource - wrap it into a service

.service('Ninja', function($resource){ var Ninja = $resource('http://192.168.105.130:3000/api/ninja/:_id', {_id: '@_id'}); return Ninja;});

Page 24: Angular Intermediate

$resource - Controller, load ninjas and go on

.controller('NinjaCtrl', function($scope, Ninja){$scope.ninjas = [];

// TODO GetAll, CreateNew, Update, Delete $scope.loadNinja = function(){ $scope.ninjas = Ninja.query(); };

...});

Page 25: Angular Intermediate

$resource - Custom methods

{

action1: {method:?, params:?, isArray:?, headers:?, ...},

action2: {method:?, params:?, isArray:?, headers:?, ...},

...

}

Page 26: Angular Intermediate

$resource - Custom method example

var Ninja = $resource('http://127.0.0.1:3000/api/ninja/:_id', {_id: '@_id'}, {

count: {method:'GET', url: 'http://127.0.0.1:3000/api/ninja/count'}});

// our custom method is mapped as well.

Ninja.count();

Page 27: Angular Intermediate

2° Lesson

form validation, directive

Page 28: Angular Intermediate

Let’s use the built in Angular form validation

Page 29: Angular Intermediate

ngForm - validation

http://codepen.io/sevilayha/full/xFcdI/

Page 30: Angular Intermediate

ngForm - validation - Property | classes

● $valid | .ng-valid● $invalid | .ng-invalid● $pristine | .ng-pristine● $dirty | .ng-dirty● $touched | .ng-touched

Page 31: Angular Intermediate

ngForm - validation - Other properties

● $submitted● $error

With $error property we can target every different errors in the form:

myForm.$error.requiredmyForm.$error.minlengthmyForm.$error.maxlength

Page 32: Angular Intermediate

ngForm - validation - access properties

● formName.propertyex: “createForm.$valid”

● formName.inputName.propertyex: “createForm.age.$pristine”

Page 33: Angular Intermediate

ngForm - input directive (with ng-model)

https://docs.angularjs.org/api/ng/directive/input

Page 34: Angular Intermediate

ngForm - custom errors

Page 35: Angular Intermediate

Directives

Directives makes HTML interactive by attaching event listeners to elements and/or transforming the DOM.

Page 36: Angular Intermediate

Angular directive

● ng-model● ng-repeat● ng-show

<input ng-model=”name” /><div ng-repeat=”item in items”></div>

Page 37: Angular Intermediate

Angular custom directive

<ng-intermediate />or

<div ng-intermediate></div>

simple object configuration

Page 38: Angular Intermediate

● no scope => parent’s scope.● scope: true => child scope● scope: {} => isolated scope

With isolate scope:● @ => Attribute string binding● = => Two-way model binding● & => Callback method binding

directive scope

Page 39: Angular Intermediate

directive scope example

<ng-intermediate cheering=”{{hello}}” name=”class” />

Page 40: Angular Intermediate

directive isolated scope explained

● @ binding is for passing strings. These strings support {{}} expressions for interpolated values.

For example: . The interpolated expression is evaluated against directive's parent scope.

● = binding is for two-way model binding. The model in parent scope is linked to the model in the

directive's isolated scope. Changes to one model affects the other, and vice versa.

● & binding is for passing a method into your directive's scope so that it can be called within your

directive. The method is pre-bound to the directive's parent scope, and supports arguments. For

example if the method is hello(name) in parent scope, then in order to execute the method from

inside your directive, you must call $scope.hello({name:'world'})

Page 41: Angular Intermediate

directive link function

The link function is mainly used for attaching event listeners to DOM elements, watching model properties for changes, and updating the DOM.

Page 42: Angular Intermediate

directive link function attributes

● scope – The scope passed to the directive. ● el – The jQLite (a subset of jQuery) wrapped

element on which the directive is applied. ● attr – An object representing normalized

attributes attached to the element on which the directive is applied.

Page 43: Angular Intermediate

directive link function example

Page 44: Angular Intermediate

directive require

Page 45: Angular Intermediate

Directive Definition Object

● https://docs.angularjs.org/api/ng/service/$compile

● https://docs.angularjs.org/guide/directive

Page 46: Angular Intermediate

Let’s build our custom validation

Page 47: Angular Intermediate

Register a custom directive

Page 48: Angular Intermediate

Configure our custom directive

Page 49: Angular Intermediate

Add the validation logic

Page 50: Angular Intermediate

3° Lesson

Modularization Path to Angular 2

Page 51: Angular Intermediate

What is a Module?

You can think of a module as a container for the different parts of your app

Page 52: Angular Intermediate

Let’s modularize the app

Page 53: Angular Intermediate

App structure - Angular 1.x

Page 54: Angular Intermediate

App structure - Angular > 1.3

Page 55: Angular Intermediate

Ideas?

Page 56: Angular Intermediate

Let’s modularize the app

ninja-list

ninja-tile

ninja-handle

Page 57: Angular Intermediate

Let’s start by creating component as a directive.

We will use directive definition object where we declare controller, controllerAs, templateUrl, and bindToController properties.

Page 58: Angular Intermediate

Directive Definition Object

https://docs.angularjs.org/guide/directive

Page 59: Angular Intermediate

ControllerAs

ControllerAs syntax enables controller to live and do their job without being bound (only) on $scope.

Page 60: Angular Intermediate

bindToController (new in Angular 1.3.X)

When used, properties from isolated scope will be automatically bound to controller’s this.

Page 61: Angular Intermediate

Example

Page 62: Angular Intermediate

Let’s do it together

Page 63: Angular Intermediate

Exercise App structure

Page 64: Angular Intermediate

Exercise ninja.module.js

Page 65: Angular Intermediate

Exercise <ninja-list>

Page 66: Angular Intermediate

● Create a new module with a new routing● Create one component for every part of the app● Every component should have one controller

and one view

Exercise

Page 67: Angular Intermediate

4° Lesson

test test test

Page 68: Angular Intermediate

Testing Theory

Page 69: Angular Intermediate

What tests are?

Automated software testing

is a process in which software tools

execute pre-scripted tests

on a software application

before it is released into production.

Page 70: Angular Intermediate

Tests Typologies

Unit Tests

A unit test is an automated piece of code that invokes a unit of work in the system and then checks a single assumption about the behavior of that unit of work.

➔ Has full control over all the pieces running (Use mocks)

➔ Can be run in any order if part of many other tests

➔ Runs in memory (no DB or File access, for example)

➔ Consistently returns the same result

➔ Tests a single logical concept in the system

➔ Readable and Maintainable

End to End Tests

End-to-end testing is a methodology used to test whether the flow of an application is performing as designed from start to finish.

➔ Use the real code (no mocks)

➔ Test Integration between components

➔ Test a workflow (eg: Registration, Profile Update, …)

➔ Run in a real Environment

Page 71: Angular Intermediate

What to be tested?

Unit Tests

➔ Complex Algorithm

➔ Shared Functions

➔ Core Functions

E2E Tests

➔ Complex Workflows

➔ Business Value

➔ Smoke Test

Page 73: Angular Intermediate

How test are structured

A suite that describe what is going to be tested

Some specs that verify a behaviour

Some expectations that assert a result

Setup and Cleanup before and after each test

Page 74: Angular Intermediate

How test are structured

Page 75: Angular Intermediate

Suites - Describe

Describe blocks:

➔ Used to wrap spec from the same component➔ Can be nested➔ Should be verbose➔ Can be skipped (xdescribe)

Page 76: Angular Intermediate

Spec - It

It blocks:

➔ Used to wrap expectations for the same unit➔ Can NOT be nested➔ Should be verbose➔ Can be skipped (xit)➔ Should test only one behaviour

Page 77: Angular Intermediate

Setup and Cleanup

before, beforeEach, after, afterEach blocks:

➔ Used to setup/cleanup the test environment➔ Mock the data➔ Mock external Unit➔ Mock the backend➔ Can NOT be nested

Page 78: Angular Intermediate

Let’s test our components

Page 79: Angular Intermediate

Our modularized app

ninja-list

ninja-tile

ninja-handle

Page 80: Angular Intermediate

Getting StartedUnit Tests - Environment Setup

Page 81: Angular Intermediate

Setting up Karma Environment

In order to execute Unit Tests we need:

➔ A test runner (Karma)➔ An assertion library (Jasmine)➔ A browser in which run the tests (PhantomJs)➔ A configuration File➔ One spec (at least)➔ A script to run the test (npm test)

Page 82: Angular Intermediate

Setting up Karma Environment

npm install

jasmine-core

karma

karma-jasmine

karma-mocha-reporter karma-ng-html2js-preprocessor karma-phantomjs-launcher

phantomjs

--save-dev

Page 83: Angular Intermediate

Karma CLI

Optionally Install:

npm install -g karma-cli

Then, you can run Karma simply by karma from anywhere

and it will always run the local version.

Page 84: Angular Intermediate

Karma Configuration File

By default the configuration file is called:

karma.conf.jshttp://karma-runner.github.io/0.8/config/configuration-file.html

karma init is an helper to generate this file

Page 85: Angular Intermediate

Karma Configuration File

What’s inside:➔ Base path: path that will be used to resolve all patterns

➔ Assertion framework: (Jasmine) complete list here

➔ Files to be loaded: Spec and application files

➔ Browser: Test environment

➔ Preprocessors*: Babel, Html2js, ...

➔ Reporters: Formatter for the test output (Mocha)

Page 86: Angular Intermediate

Npm Test

It’s a common practice to define a script called:

npm test

"scripts": {"test": "karma start"}

Page 87: Angular Intermediate

Exercise

Page 88: Angular Intermediate

ninja-list -> What to test?

● Variable in scope

● Function in scope

● Html render

Page 89: Angular Intermediate

ninja-list -> show me the code

Page 90: Angular Intermediate

$httpBackend

Fake HTTP backend implementation suitable for unit testing applications that use the $http service.

https://docs.angularjs.org/api/ngMock/service/$httpBackend

Page 91: Angular Intermediate

$httpBackend -> How we use it

var serverMock = [{'age': 55, 'name': 'Daniele', '_id': '0'}, {'age': 35, 'name': 'Marco', '_id': '1'}];

Page 92: Angular Intermediate

Flushing HTTP requests

flush() method, allows the test to explicitly flush pending requests. This preserves the async api of the backend, while allowing the test to execute synchronously.

Page 93: Angular Intermediate

ninja-list (beforeEach) final

Page 94: Angular Intermediate

The end

questions?

Page 96: Angular Intermediate

Links

*** If you are not there already: http://meanmilan.herokuapp.com/

● http://linkme.it/

● https://github.com/linkmesrl/ngIntermediate

● https://meanmilan.slack.com/ ***