Angular wwc

39
Angular Workshop --Sowju Mudunuri

Transcript of Angular wwc

Angular Workshop

--Sowju Mudunuri

Disclaimer

• These slides are a composition of various resources I found on the internet and is not an original content of me

• The primary intent of the slides is to teach myself angular and better organization of keypoints of all things Angular if I have to review

• The other intent is to help my friends who are learning angular to give a direction

Resources/References

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

• https://code.angularjs.org/1.2.25/docs/guide/

• ng-book

• codeschool

• pluralsight

• blogs

• Developing Backbone Applications by AddyOsmani

Browser Object Model

• Provides objects that expose browser functionality

• Window object, represents an instance of the browser

• Location object provides information about the document that is currently loaded in the window

Document Object Model

• provides an API to interact with HTML and XML documents

• it allows developers to add, remove and modify parts of the page by representing the HTML document as a hierarchical tree of nodesdocument.getElementById(‘some’)

document.getElementByTagName(‘another’)

Callbacks

Callbacks: functions that are passed to other functions as arguments

function interviewSuccess(callback) {

//do something ..

callback();

//….

}

function practiceProblems() {

//...work hard

}

interviewSuccess(practiceProblems);

Traditional Web Pages

• Required a complete page reload when moving between pages

Problems:

• A great deal of duplicated content being served back to the user

• It affects latency and responsiveness of the user experience

Single Page Apps

• Apps for which after an Initial page load the subsequent navigations doesnot require a page load

• When a user navigates to a new view, the application requests additional content for the view using a XHR(XMLHTTPRequest), typically communicating with a server-side REST API

• Frameworks: Angular, Backbone, Ember, React ..

Angular

• It’s a Javascript Framework that runs in the browser

• ng stands for ANGULAR• ng-app initializes the app with that particular

dom element and the child elements• angular is one identifier that angular puts in the

global namespace so you can call different methods

• angular.element is an alias for Jquery function• If Jquery is not available it uses the built-in subset

of jquery called jqLite

Angular Basics

• HTML as a templating language

• Two way data-binding

• Directives

• Dependency Injection

• https://code.angularjs.org/

Data Binding

• Automatic synchronization of data between model and view

• The way angular implements data binding lets you treat the model as the single source of truth in your application

• View is a projection of model at all times

• Any changes to the view are immediately reflected in the model and any changes in the model are immediately reflected on the view

Directives

• are markers on DOM elements that tell the HTML compiler($compile) to attach a specified behavior to that DOM element or even transform the DOM element

• We register a directive using module.directivemethod

• types of directives: Element, Attribute, Class• Use Cases: resusable html code, DOM

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

Commonly used directives

• ng-app

• ng-controller

• ng-click

• ng-model

• ng-show

• ng-hide

• ng-class

• ng-repeat

Commonly used directives

• ng-submit

• ng-src

• ng-init

• ng-options

• ng-change

Deep Dive into Directives

ng-app

• is used to bootstrap an AngularJS application

• only one angular-js application can be bootstrapped per HTML document

• accepts an optional application module name to load

Deep Dive into Directives

ng-init: allows you to evaluate an expression in the current scope

ng-model: binds an input, select, textarea to a property on the scope

ng-show/ng-hide: shows or hides the given HTML element based on the expression provided to the ng-show attribute

ng-controller: attaches a controller class to the view.

MVC in Angular

Models: properties on the scope

View: The template(HTML with data bindings) that is rendered into the View

Controller: contains the business logic behind the application to decorate the scope with functions and values

Controllers

• Controllers are javascript functions that are used to augment the angular scope

• When the controller is attached to the DOM via ng-controller directive, angular will instantiate a new controller object using the specified constructor function

• A new child scope is available as an injectable parameter to the controllers constructor function as $scope

• You can attach something on the $scope like $scope.message

• setup the model data and bind it to the view• binding expressions in view look for the models on the

scope

Controllers

Use them to 1) setup initial state of the $scope object2) add behavior to the $scope object

Don’t use them to 1) manipulate the DOM2) format input3) filter input4) share code

More on Controllers

• The properties you attach to $scope object constitutes the model that is going to be used in the view

• All properties on the $scope are available to the template at that point in the DOM where the controller is registered

• we don’t normally have controllers in the global namespace.

• Angular module as a home for a controller

Module

• Container for the different parts of your app-controllers, services, filters, directives

• you can package code as reusable components

• Instead of having the code sit in one single file you can split up the code based on features

• Convention: Is to have a module for each feature and an application level module which depends on the above modules and contains any initialization code

Module API

• is an interface for configuring angular modules

• commonly used methods are

- factory

- filter

- controller

- directive

- config

- run

angular.module

• It’s a global place for creating, registering and retrieving angular modules

• all modules that should be available to an application must be registered using this mechanism

• angular.module(“sleepEarly”, []); creates a new module

• angular.module(“sleepEarly”); retrieves an existing module

Exercise Time !

Services

• Services are singleton objects that are instantiated only once per app(by the $injector) and lazy-loaded(created only when necessary). They provide an interface to keep together those methods that relate to a specific function.

• To use an angular service, you add it as a dependency for the component(controller, service, filter or directive) that depends on the service

More on services

• Angular services are substitutable objects that are wired together using dependency injection

• You can use services to organize and share code across your app

• Services can have their own dependencies. Just like declaring dependencies in a controller, you declare dependencies by specifying them in the services factory function signature

Why Services?

• For memory and performance purposes, controllers are instantiated only when they are needed and discarded when they are not. That means that every time we switch a route or reload a view, the current controller gets cleaned up by Angular.

• Services provide a method for us to keep data around for the lifetime of the app and communicate across controllers in a consistent manner.

Configuring existing services

• You can use the ‘config’ method on the MODULE API to configure existing services

• with this method you can register work that needs to be performed on module loading

Creating services

• you can register a service using module#factory method

• it returns an object or a function that represents the service which can injected into any component that specifies the service as a dependency

$location

• It parses the URL in the browser address bar based on window.location and makes the url available in your application

• Syncs the url with the browser when the user changes the address bar clicks the back or forward button

commonly used methods are• $location.path• $location.url• $location.host• $location.search• $location.hash

$http

• It’s a core angular service that facilitates communication with remote HTTP servers using browsers XMLHTTPRequest object

Exercise Time!

$route

• $route is used for deep-linking URLs to controllers and views. It watches $location.url() and tries to map the path to an existing route definition.

• Requires the ngRoute module to be installed

• You can define routes through $routeProvider’sAPI

• $route service is used in conjunction with the ngView directive and the $routeParams service

Switching Views based on routes

• ng-view: is a directive that complements the $route service by including the rendered template of the current route into the main layout file.

• Everytime the current route changes, the included view changes with it accordingly to the confuguration of the $route service

Custom Directives

• Register a Directive: Directives are registered on Modules using the module.directive API.

• module.directive API takes the normalized directive name followed by a factory function

• The factory function should return an object that describes how the directive should behave

More on Custom directives

• Directives can be

1) Attribute with ‘restrict: A’

2) Element with ‘restrict: E’

3) Class with ‘restrict: C’

Isolate Scope

• Without an isolate scope we need to create a new controller in order to reuse a directive

• With isolate scope we separate the scope inside the directive to the scope outside the directive and then map the outer scope to the inner scope

• To do this we use the directives scope option

Isolate scope.directive('myCustomer', function() {

return {restrict: 'E',scope: {

customerInfo: '=info'},templateUrl: 'my-customer-iso.html'

};

});

angular.module('docsIsolateScopeDirective', []).controller('Controller', ['$scope', function($scope) {

$scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };$scope.igor = { name: 'Igor', address: '123 Somewhere' };

}])

<my-customer info="naomi"></my-customer><hr><my-customer info="igor"></my-customer>

More

• Most production applications most javascriptgoes through a minifier hence we need a different syntax for controller dependency injection using $injector

• angular.element($0).scope