Angular is a web application framework developed in 2009. It allows developers to create single page applications using HTML enhanced with Angular specific directives and by associating angular components like controllers, services and filters with HTML. The document provides an overview of key Angular concepts like controllers, services, filters and routing and how they are used to build interactive single page applications. It also demonstrates how to make HTTP requests to backend services and handle promises using the $http service and $q.
- Angular modules help organize an application into blocks of related functionality. Modules declare components, directives, pipes and services that belong to that module.
- There are different types of modules like root modules, feature modules, and shared modules. The root module launches the app. Feature modules extend functionality. Shared modules contain reusable constructs.
- Modules can import and export specific constructs to make them available to other modules. Services declared in a module are singletons app-wide unless the module is lazy loaded. Core modules contain global services imported by the root module only.
This document provides an overview of Angular 2 and Rxjs. Some key points covered include:
- Angular 2 is backed by Google and designed to be faster and more memory efficient than Angular 1. It uses TypeScript and focuses on components.
- Bootstrapping, modules, directives, bindings and pipes work differently in Angular 2 compared to Angular 1 with fewer overall concepts.
- Observables and operators from Rxjs allow for asynchronous programming and composing asynchronous operations. Common operators like map, filter and flatMap are discussed.
- Services can be used to share data between components. Components follow a lifecycle with hooks like ngOnInit and ngOnDestroy.
-
This document provides an overview of Angular, including:
- Angular is a JavaScript framework used to build client-side applications with HTML. Code is written in TypeScript which compiles to JavaScript.
- Angular enhances HTML with directives, data binding, and dependency injection. It follows an MVC architecture internally.
- Components are the basic building blocks of Angular applications. Modules contain components and services. Services contain reusable business logic.
- The document discusses Angular concepts like modules, components, data binding, services, routing and forms. It provides examples of creating a sample login/welcome application in Angular.
This document discusses data flow patterns in Angular 2. It begins by explaining the component tree structure and how components communicate with inputs and outputs. It then covers RxJS observables and operators for reactive programming. Observables can be used as inputs to components and with the async pipe. Forms and HTTP requests also return observables. Change detection strategies like OnPush can improve performance. Immutable data structures help avoid unnecessary checks. Overall, Angular 2 provides many options for component communication through RxJS observables and efficient change detection.
Probabilmente il framework javascript più atteso di sempre, evoluzione di uno dei framework più longevi ed usati nello sviluppo front end. Si vedranno alcune delle novità introdotte e delle scelte radicali fatte da Google per la nuova versione di Angular
This document discusses dependency injection in Angular. It shows how to create injectors that provide dependencies to injectables. It demonstrates hierarchical injectors where child injectors inherit from parent injectors. It also covers how to provide dependencies through the @Injectable decorator, modules, and directly in the bootstrap process. View injectors are discussed as well as querying for dependencies from components, directives and templates.
Modularizing a project is never easy, a lot of files to move and the dependencies between them is not always what we expect. Then the Dagger configuration used in a single module project often doesn't scale well to a multi module project. Hilt is opinionated about the configuration to use (we don't need to argue anymore about using component dependencies or subcomponents!) and this configuration works perfectly even in a multi module project. In this talk we'll see first an introduction to Hilt and a comparison with Dagger to understand why it's easier to configure. Then we'll see how to leverage it in a multi module project (both in a standard layered architecture and in a Clean Architecture that uses the Dependency Inversion) to improve build speed and code testability. Spoiler alert: using sample apps that include a single feature in the app helps a lot!
- Angular modules help organize an application into blocks of related functionality. Modules declare components, directives, pipes and services that belong to that module.
- There are different types of modules like root modules, feature modules, and shared modules. The root module launches the app. Feature modules extend functionality. Shared modules contain reusable constructs.
- Modules can import and export specific constructs to make them available to other modules. Services declared in a module are singletons app-wide unless the module is lazy loaded. Core modules contain global services imported by the root module only.
This document provides an overview of Angular 2 and Rxjs. Some key points covered include:
- Angular 2 is backed by Google and designed to be faster and more memory efficient than Angular 1. It uses TypeScript and focuses on components.
- Bootstrapping, modules, directives, bindings and pipes work differently in Angular 2 compared to Angular 1 with fewer overall concepts.
- Observables and operators from Rxjs allow for asynchronous programming and composing asynchronous operations. Common operators like map, filter and flatMap are discussed.
- Services can be used to share data between components. Components follow a lifecycle with hooks like ngOnInit and ngOnDestroy.
-
This document provides an overview of Angular, including:
- Angular is a JavaScript framework used to build client-side applications with HTML. Code is written in TypeScript which compiles to JavaScript.
- Angular enhances HTML with directives, data binding, and dependency injection. It follows an MVC architecture internally.
- Components are the basic building blocks of Angular applications. Modules contain components and services. Services contain reusable business logic.
- The document discusses Angular concepts like modules, components, data binding, services, routing and forms. It provides examples of creating a sample login/welcome application in Angular.
This document discusses data flow patterns in Angular 2. It begins by explaining the component tree structure and how components communicate with inputs and outputs. It then covers RxJS observables and operators for reactive programming. Observables can be used as inputs to components and with the async pipe. Forms and HTTP requests also return observables. Change detection strategies like OnPush can improve performance. Immutable data structures help avoid unnecessary checks. Overall, Angular 2 provides many options for component communication through RxJS observables and efficient change detection.
Probabilmente il framework javascript più atteso di sempre, evoluzione di uno dei framework più longevi ed usati nello sviluppo front end. Si vedranno alcune delle novità introdotte e delle scelte radicali fatte da Google per la nuova versione di Angular
This document discusses dependency injection in Angular. It shows how to create injectors that provide dependencies to injectables. It demonstrates hierarchical injectors where child injectors inherit from parent injectors. It also covers how to provide dependencies through the @Injectable decorator, modules, and directly in the bootstrap process. View injectors are discussed as well as querying for dependencies from components, directives and templates.
Modularizing a project is never easy, a lot of files to move and the dependencies between them is not always what we expect. Then the Dagger configuration used in a single module project often doesn't scale well to a multi module project. Hilt is opinionated about the configuration to use (we don't need to argue anymore about using component dependencies or subcomponents!) and this configuration works perfectly even in a multi module project. In this talk we'll see first an introduction to Hilt and a comparison with Dagger to understand why it's easier to configure. Then we'll see how to leverage it in a multi module project (both in a standard layered architecture and in a Clean Architecture that uses the Dependency Inversion) to improve build speed and code testability. Spoiler alert: using sample apps that include a single feature in the app helps a lot!
Slides for our (John Rodriguez and myself) talk at Droidcon SF: http://sf.droidcon.com/schedule
For the past 3 years, Square Register Android has leveraged Dagger † to wire up Java objects. However, the app scope hierarchy and complexity increased and we started having bugs and crashes related to scoping errors. This talk will show how to structure an app around Dagger2 ‡ and present a strategy for incrementally migrating from Dagger1 to Dagger2.
This document provides an overview of Angular 2 architecture, components, dependency injection, bindings, pipes and the migration path from AngularJS. Some key points:
- Angular 2 uses a component-based architecture where everything is a component. Components can be nested to form a component tree.
- Components are defined using annotations like @Component and @View. Templates, styles and other metadata can be associated with a component.
- Dependency injection allows injecting services into components via the constructor. Services are singletons available via the injector.
- Data binding in Angular 2 allows binding component properties and events to the template using property, event and two-way bindings.
- P
This document provides an overview of key concepts in Angular 2, including:
- Components form the building blocks of an Angular 2 application and use metadata to configure selector, template, and more.
- Templates can be defined inline using TypeScript template strings or external template files.
- Property and event bindings allow components to share data and handle user input.
- Dependency injection provides services to components through their constructors similarly to AngularJS but with additional capabilities like child injectors.
- Pipes allow transforming values in templates similarly to filters in AngularJS.
- Annotations like @Component and @View configure components.
- The framework is actively developed with an
This document outlines an agenda for an Angular2 workshop. The workshop will introduce Angular2 concepts and components, teach how to build an application using components, and cover routing and business logic. Attendees will build a restaurant ordering application to learn how to compose components, implement routing, create data models and services, and connect to backend servers. The workshop is broken into three parts - components, routing, and business logic. Attendees will work through building pieces of the application, with checkpoints provided to see working examples.
The document discusses Angular modules and NgModules. It shows different types of NgModule declarations including components, directives, and pipes. It also shows the different NgModule metadata properties like imports, exports, declarations, and providers. It demonstrates how modules can import and export declarations and how modules are loaded within the application injector.
Angular 2 is the next version of the AngularJS framework. It was released in 2016 after 2 years of development. Some key features of Angular 2 include optimized performance for both desktop and mobile applications, ahead of time compilation for faster loading, and native support for reactive programming. The document then provides examples of core Angular concepts like components, directives, services, dependency injection and change detection. It explains how Angular 2 applications are bootstrapped and discusses some of the internal workings like the change detection engine.
Angular server side rendering - Strategies & Technics Eliran Eliassy
Server Side Rendering (SSR) involves running and serving an Angular application from the server. This provides benefits like fast initial loading, SEO/crawlability since search engines can't run JavaScript. The document discusses SSR strategies like partial rendering and avoiding duplicate requests. It also covers challenges like unsupported features and outlines steps to implement SSR like generating a Universal module and rendering on the server with Express. SSR can improve performance but requires more complex setup and deployment.
The document provides an overview of AngularJS, including its core concepts and how it can be used with Java frameworks like Spring, Struts, and Hibernate. AngularJS is an open-source JavaScript framework that assists with building single-page applications using MVC architecture. It allows developers to specify custom HTML tags and directives to control element behavior. The document then discusses key AngularJS concepts like data binding, directives, expressions, filters, controllers, dependency injection, views/routing, and services. It provides examples of how these concepts work and how AngularJS can integrate with Java frameworks in a sample reader application divided into multiple sub-projects.
This document provides an overview of Angular 2, including:
- Angular 2 is a rewrite of AngularJS and introduces many breaking changes.
- It uses Typescript as its language and compiles to plain JavaScript.
- Key concepts include components, templates, directives, dependency injection, and services.
- Components define views using templates, styles, and class logic. They can communicate via inputs and outputs.
- Directives add behavior to the existing DOM using selectors like elements, attributes, or classes.
The document provides best practice guidelines for developing Angular applications from version 2 to 6. It covers topics such as file structure conventions, naming conventions, coding conventions, component guidelines, directives, services and more. The guidelines aim to promote consistency, readability and maintainability of Angular codebases.
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Ontico
The document discusses how Angular components can "parasitize" the React ecosystem. It begins by providing code examples of basic Angular component creation. It then explores terminology related to parasitism and parasitoids. Various approaches for communicating between Angular components using services, properties, and Redux are presented. The document also discusses ideas for libraries that could help convert React components to Angular. It covers tools and patterns for state management in Angular like Redux and MobX. Finally, it discusses how Angular components could potentially "parasitize" the React ecosystem in both helpful and harmful ways.
There are multiple ways to style a component in Angular. This slide was created for my talk at AngularIL August meet up and contains recepis for styling.
JSF (JavaServer Faces) provides an event model, validation model, and conversion model to handle user input and events in web applications. The event model defines different event types like action, value change, and phase events that allow components to notify listeners of user interactions. The validation model validates user input on UI components using standard and custom validators. The conversion model converts between view data types like strings and model data types using standard and custom converters.
The document discusses building native components and modules for React Native applications. It provides guidance on creating native modules and components for both iOS and Android platforms. For native modules, it describes how to expose methods and properties to JavaScript. For native components, it explains how to create custom native views and expose their properties and events to React components.
AngularJS is a popular JavaScript framework. It is intended to make the implementation of RIA (Rich Internet Applications) easier and convenient. AngularJS is created and maintained by Google. It is relatively, a new JavaScript framework, which is designed to make the front-end development as simple as possible. AngularJS is a useful tool for standardizing the web application structure and it provides a future template to ensure that the client-side applications are developed much effectively.
This document by RapidValue is written by Gourav Ajmani, Technical Lead, who has been working on AngularJS for a while, and has read many tutorials and blogs on it. According to Gourav, he could never find any article which gives a clear, concise and step-by-step guide to create the project structure and execute the project. So, he has written this document which will help you to create the Project structure and then execute it in a simple manner.
This document provides an overview of Angular 2 and its main building blocks including modules, components, templates, data binding, directives, services, and routing. It discusses how Angular 2 differs from Angular 1 and is more opinionated. It also provides code examples for setting up the main module, creating components and templates, using dependency injection for services, and making HTTP requests from services.
AngularJS seems initially complex with many new concepts and terms. It is designed for single page applications and has a learning curve. AngularJS uses modules, dependency injection, MVC principles, scopes, directives, filters and services/factories/providers to build applications. Testing and reusable components are important. While challenging, AngularJS is a powerful tool for building dynamic web applications.
Dependency Injection pattern in AngularAlexe Bogdan
The document discusses dependency injection (DI) in Angular and how it is used to configure services. It provides examples of different service types - constant, value, factory, service, and provider - and how they are registered and injected. The ngRoute module is also summarized as the core routing module in Angular that uses directives to render templates based on routes.
Typescript fundamentals document summarized in 3 sentences:
The document discusses Typescript fundamentals including types, classes, interfaces, modules and how to use the Typescript compiler. It explains how Typescript adds type safety and compile time checking to JavaScript by using types for variables, parameters, returns and more. Examples are provided for many Typescript features and how they compile down to equivalent JavaScript.
This document provides an overview of Rxjs (Reactive Extensions for JavaScript). It begins by explaining why Rxjs is useful for dealing with asynchronous code in a synchronous way and provides one paradigm for asynchronous operations. It then discusses the history of callbacks and promises for asynchronous code. The bulk of the document explains key concepts in Rxjs including Observables, Operators, error handling, testing with Schedulers, and compares Promises to Rxjs. It provides examples of many common Rxjs operators and patterns.
Slides for our (John Rodriguez and myself) talk at Droidcon SF: http://sf.droidcon.com/schedule
For the past 3 years, Square Register Android has leveraged Dagger † to wire up Java objects. However, the app scope hierarchy and complexity increased and we started having bugs and crashes related to scoping errors. This talk will show how to structure an app around Dagger2 ‡ and present a strategy for incrementally migrating from Dagger1 to Dagger2.
This document provides an overview of Angular 2 architecture, components, dependency injection, bindings, pipes and the migration path from AngularJS. Some key points:
- Angular 2 uses a component-based architecture where everything is a component. Components can be nested to form a component tree.
- Components are defined using annotations like @Component and @View. Templates, styles and other metadata can be associated with a component.
- Dependency injection allows injecting services into components via the constructor. Services are singletons available via the injector.
- Data binding in Angular 2 allows binding component properties and events to the template using property, event and two-way bindings.
- P
This document provides an overview of key concepts in Angular 2, including:
- Components form the building blocks of an Angular 2 application and use metadata to configure selector, template, and more.
- Templates can be defined inline using TypeScript template strings or external template files.
- Property and event bindings allow components to share data and handle user input.
- Dependency injection provides services to components through their constructors similarly to AngularJS but with additional capabilities like child injectors.
- Pipes allow transforming values in templates similarly to filters in AngularJS.
- Annotations like @Component and @View configure components.
- The framework is actively developed with an
This document outlines an agenda for an Angular2 workshop. The workshop will introduce Angular2 concepts and components, teach how to build an application using components, and cover routing and business logic. Attendees will build a restaurant ordering application to learn how to compose components, implement routing, create data models and services, and connect to backend servers. The workshop is broken into three parts - components, routing, and business logic. Attendees will work through building pieces of the application, with checkpoints provided to see working examples.
The document discusses Angular modules and NgModules. It shows different types of NgModule declarations including components, directives, and pipes. It also shows the different NgModule metadata properties like imports, exports, declarations, and providers. It demonstrates how modules can import and export declarations and how modules are loaded within the application injector.
Angular 2 is the next version of the AngularJS framework. It was released in 2016 after 2 years of development. Some key features of Angular 2 include optimized performance for both desktop and mobile applications, ahead of time compilation for faster loading, and native support for reactive programming. The document then provides examples of core Angular concepts like components, directives, services, dependency injection and change detection. It explains how Angular 2 applications are bootstrapped and discusses some of the internal workings like the change detection engine.
Angular server side rendering - Strategies & Technics Eliran Eliassy
Server Side Rendering (SSR) involves running and serving an Angular application from the server. This provides benefits like fast initial loading, SEO/crawlability since search engines can't run JavaScript. The document discusses SSR strategies like partial rendering and avoiding duplicate requests. It also covers challenges like unsupported features and outlines steps to implement SSR like generating a Universal module and rendering on the server with Express. SSR can improve performance but requires more complex setup and deployment.
The document provides an overview of AngularJS, including its core concepts and how it can be used with Java frameworks like Spring, Struts, and Hibernate. AngularJS is an open-source JavaScript framework that assists with building single-page applications using MVC architecture. It allows developers to specify custom HTML tags and directives to control element behavior. The document then discusses key AngularJS concepts like data binding, directives, expressions, filters, controllers, dependency injection, views/routing, and services. It provides examples of how these concepts work and how AngularJS can integrate with Java frameworks in a sample reader application divided into multiple sub-projects.
This document provides an overview of Angular 2, including:
- Angular 2 is a rewrite of AngularJS and introduces many breaking changes.
- It uses Typescript as its language and compiles to plain JavaScript.
- Key concepts include components, templates, directives, dependency injection, and services.
- Components define views using templates, styles, and class logic. They can communicate via inputs and outputs.
- Directives add behavior to the existing DOM using selectors like elements, attributes, or classes.
The document provides best practice guidelines for developing Angular applications from version 2 to 6. It covers topics such as file structure conventions, naming conventions, coding conventions, component guidelines, directives, services and more. The guidelines aim to promote consistency, readability and maintainability of Angular codebases.
Паразитируем на React-экосистеме (Angular 4+) / Алексей Охрименко (IPONWEB)Ontico
The document discusses how Angular components can "parasitize" the React ecosystem. It begins by providing code examples of basic Angular component creation. It then explores terminology related to parasitism and parasitoids. Various approaches for communicating between Angular components using services, properties, and Redux are presented. The document also discusses ideas for libraries that could help convert React components to Angular. It covers tools and patterns for state management in Angular like Redux and MobX. Finally, it discusses how Angular components could potentially "parasitize" the React ecosystem in both helpful and harmful ways.
There are multiple ways to style a component in Angular. This slide was created for my talk at AngularIL August meet up and contains recepis for styling.
JSF (JavaServer Faces) provides an event model, validation model, and conversion model to handle user input and events in web applications. The event model defines different event types like action, value change, and phase events that allow components to notify listeners of user interactions. The validation model validates user input on UI components using standard and custom validators. The conversion model converts between view data types like strings and model data types using standard and custom converters.
The document discusses building native components and modules for React Native applications. It provides guidance on creating native modules and components for both iOS and Android platforms. For native modules, it describes how to expose methods and properties to JavaScript. For native components, it explains how to create custom native views and expose their properties and events to React components.
AngularJS is a popular JavaScript framework. It is intended to make the implementation of RIA (Rich Internet Applications) easier and convenient. AngularJS is created and maintained by Google. It is relatively, a new JavaScript framework, which is designed to make the front-end development as simple as possible. AngularJS is a useful tool for standardizing the web application structure and it provides a future template to ensure that the client-side applications are developed much effectively.
This document by RapidValue is written by Gourav Ajmani, Technical Lead, who has been working on AngularJS for a while, and has read many tutorials and blogs on it. According to Gourav, he could never find any article which gives a clear, concise and step-by-step guide to create the project structure and execute the project. So, he has written this document which will help you to create the Project structure and then execute it in a simple manner.
This document provides an overview of Angular 2 and its main building blocks including modules, components, templates, data binding, directives, services, and routing. It discusses how Angular 2 differs from Angular 1 and is more opinionated. It also provides code examples for setting up the main module, creating components and templates, using dependency injection for services, and making HTTP requests from services.
AngularJS seems initially complex with many new concepts and terms. It is designed for single page applications and has a learning curve. AngularJS uses modules, dependency injection, MVC principles, scopes, directives, filters and services/factories/providers to build applications. Testing and reusable components are important. While challenging, AngularJS is a powerful tool for building dynamic web applications.
Dependency Injection pattern in AngularAlexe Bogdan
The document discusses dependency injection (DI) in Angular and how it is used to configure services. It provides examples of different service types - constant, value, factory, service, and provider - and how they are registered and injected. The ngRoute module is also summarized as the core routing module in Angular that uses directives to render templates based on routes.
Typescript fundamentals document summarized in 3 sentences:
The document discusses Typescript fundamentals including types, classes, interfaces, modules and how to use the Typescript compiler. It explains how Typescript adds type safety and compile time checking to JavaScript by using types for variables, parameters, returns and more. Examples are provided for many Typescript features and how they compile down to equivalent JavaScript.
This document provides an overview of Rxjs (Reactive Extensions for JavaScript). It begins by explaining why Rxjs is useful for dealing with asynchronous code in a synchronous way and provides one paradigm for asynchronous operations. It then discusses the history of callbacks and promises for asynchronous code. The bulk of the document explains key concepts in Rxjs including Observables, Operators, error handling, testing with Schedulers, and compares Promises to Rxjs. It provides examples of many common Rxjs operators and patterns.
Angular2 is better, faster, and stronger than Angular1 in several ways:
1. Angular2 improves change detection, reduces concepts, and uses TypeScript as a first-class citizen.
2. Features like AOT, tree shaking, lazy loading, and RxJS observables make Angular2 faster and more efficient.
3. Angular2 has an upgrade path and is focused on components, allowing it to be used everywhere from native mobile to desktop apps.
Firebase and ng2
This document discusses Firebase and AngularFire/AngularFire2. It summarizes that Firebase is a backend as a service that provides realtime database functionality. AngularFire/AngularFire2 are wrappers that make the Firebase API accessible to Angular applications. Key features covered include authentication, authorization, data validation, and working with data through observable references and promises. Best practices like shallow data structures and avoiding deep nesting are also highlighted.
1. Rxjs provides a better way of handling asynchronous code through observables which are streams of values over time. Observables allow for cancellable, retryable operations and easy composition of different asynchronous sources.
2. Common Rxjs operators like map, filter, and flatMap allow transforming and combining observable streams. Operators make observables quite powerful for tasks like async logic, event handling, and API requests.
3. In Angular, observables are used extensively for tasks like HTTP requests, routing, and component communication. Key aspects are using async pipes for subscriptions and unsubscribing during lifecycle hooks. Rxjs greatly simplifies many common asynchronous patterns in Angular applications.
Rxjs provides a paradigm for dealing with asynchronous operations in a way that resembles synchronous code. It uses Observables to represent asynchronous data streams over time that can be composed using operators. This allows handling of events, asynchronous code, and other reactive sources in a declarative way. Key points are:
- Observables represent asynchronous data streams that can be subscribed to.
- Operators allow manipulating and transforming streams through methods like map, filter, switchMap.
- Schedulers allow controlling virtual time for testing asynchronous behavior.
- Promises represent single values while Observables represent continuous streams, making Observables more powerful for reactive programming.
- Cascading asynchronous calls can be modeled elegantly using switch
The Ionic Framework command line utility makes it easy to start, build, run, and emulate Ionic apps.
Learn how to use the power of Ionic CLI, you'll see the most important commands and resources to go deeper into all goodies provided by this amazing tool.
Ionic CLI is so fun to use, after this presentation you'll feel more comfortable using the terminal while develop hybrid apps with Ionic Framework.
RxJs - demystified provides an overview of reactive programming and RxJs. The key points covered are:
- Reactive programming focuses on propagating changes without explicitly specifying how propagation happens.
- Observables are at the heart of RxJs and emit values in a push-based manner. Operators allow transforming, filtering, and combining observables.
- Common operators include map, filter, reduce, buffer, and switchMap. Over 120 operators exist for tasks like error handling, multicasting, and conditional logic.
- Marble diagrams visually demonstrate how operators transform observable streams.
- Creating observables from events, promises, arrays and iterables allows wrapping different data sources in a uniform API
This document provides an overview of React and Redux concepts including:
- React basics like components, props, state, and lifecycle methods
- Flux architecture and how data flows through actions, dispatcher, and stores
- Redux as an alternative to Flux that uses a single store updated by reducers in response to actions
- Additional React topics like JSX, propTypes, and using React with ES6 classes are also covered.
Nativescript allows building native mobile apps using JavaScript and CSS. It works by injecting native APIs into JavaScript so they can be accessed directly. This allows using native UI controls and hardware capabilities while coding in a familiar language. Nativescript apps are compiled to platform-specific code, so they are true native apps that can be submitted to app stores. It supports Angular for building apps with common code shared across platforms.
The document discusses techniques for writing clean JavaScript code. It provides examples of code smells and improvements to address issues like attaching events from the outside, separating selection from logic, shallow scope, overwriting default behavior, and separating logic from views. The document advocates for practices like modularizing functions, separating DOM manipulation from models, and creating model objects to represent DOM elements rather than directly manipulating the DOM. It encourages learning clean JavaScript techniques to write better structured and more maintainable code.
This document discusses how to mock a backend for an AngularJS application without a real backend. It recommends organizing URL definitions, creating JSON fixture files to represent mock data, using $httpBackend to mock server responses, and $resource to load local JSON files. It emphasizes using $httpBackend's dynamic response capabilities to validate requests and return custom headers. It also recommends persisting mock data using localStorage and a service to represent cached data, completing the backend simulation experience. The document provides code examples for implementing these techniques to mock CRUD operations on a user resource as part of a user ranking application.
Express is a web framework for Node.js that allows routing, middleware, templating and more. It is inspired by Sinatra and uses Connect as its middleware framework. Key features include routing, middleware support, template rendering with engines like Jade, and session handling with storage options. Errors can be handled via the app.error() method. Express provides a full-featured and easy to use web development framework for Node.js.
Come to this talk prepared to learn about the Doctrine PHP open source project. The Doctrine project has been around for over a decade and has evolved from database abstraction software that dates back to the PEAR days. The packages provided by the Doctrine project have been downloaded almost 500 million times from packagist. In this talk we will take you through how to get started with Doctrine and how to take advantage of some of the more advanced features.
Building an End-to-End AngularJS ApplicationDan Wahlin
This talk discusses how AngularJS can be used to build an end-to-end Customer Manager application. It covers structuring code and files, working with events, XHR interceptors, plus more.
This document provides an overview of key AngularJS concepts including modules, controllers, directives, services, routing, and more. It covers:
- Defining modules, controllers, services, providers, and directives
- Data binding, expressions, and controller syntax
- Working with forms, validation, and animations
- Connecting to REST APIs and working with JSON
- Using directives, isolate scopes, and the link function
- Routing applications with UI Router
- Promises, events, and advanced Angular topics
The document is a tutorial that explains AngularJS fundamentals while providing code examples for common tasks like routing, working with forms, using services, and creating directives.
Introducing Rendr: Run your Backbone.js apps on the client and serverSpike Brehm
Rendr is a JavaScript library that allows Backbone.js applications to run on both the client and server sides. It provides common classes and logic that can be reused across both environments, such as BaseView, BaseModel, and routers. On the server, it renders the HTML output using the same application logic. On the client, it hydrates the views by attaching them to the corresponding DOM elements. The goal is to write application logic in a way that is agnostic to the environment, avoiding duplicating code or context switching between client and server implementations.
Do you want a SDK with that API? (Nordic APIS April 2014)Nordic APIs
The document discusses the benefits and drawbacks of using SDKs (software development kits) to access APIs. SDKs can help reduce time-to-first-use for developers but can also introduce dependencies and long-term support costs. The document recommends SDKs for on-boarding but suggests transitioning to using web APIs directly in production to avoid issues with instrumentation, metrics, error handling and performance.
These presentation file was meant to be used in a local weekly-based meetings but hadn't have the chance of being presented.
Unfortunately this presentation file does not include all aspects of AngularJs which were supposed to be updated but it's never happened.
Anyways, hope it may come to some use.
The document discusses AngularJS modules and dependency injection. It explains that modules allow grouping of related code, and the injector resolves dependencies. It provides examples of defining modules, registering components, and the injector loading modules and resolving dependencies.
This document provides an introduction to HTML enhanced for web apps using AngularJS. It discusses key AngularJS concepts like templates (directives), controllers, dependency injection, services, filters, models, configuration, routing, resources and testing. Directives allow HTML to be extended with new attributes and elements. Controllers contain business logic. Dependency injection provides dependencies to controllers and services. Filters transform displayed data. Models represent application data. Configuration sets up modules. Routing maps URLs to templates. Resources interact with RESTful APIs. Testing ensures code works as expected.
This document discusses mashing up JavaScript applications. It covers topics like CORS and OAuth2 for API access, using local storage to store access tokens, templates with Mustache.js, and implementing real-time updates using WebSockets, ActivityStreams, and PubSubHubbub. Code examples are provided for building a JavaScript client that retrieves data from an API using OAuth2 authorization, renders content with templates, and allows posting new entries.
Optimizing Angular Performance in Enterprise Single Page AppsMorgan Stone
This document discusses strategies for optimizing Angular performance, including minimizing watchers, reducing digest cycle time, optimizing load time, and caching templates. It recommends avoiding unnecessary watches, using track by in ng-repeat, keeping controllers small and logic in services, caching requests, and pre-caching templates during build to reduce the number of HTTP requests.
Mashing up JavaScript – Advanced Techniques for modern Web AppsBastian Hofmann
This document discusses advanced JavaScript techniques for building modern web applications. It covers topics like JavaScript apps, CORS and OAuth2 for API access, local storage, templates with Mustache.js, and real-time updates using WebSockets, PubSubHubbub and ActivityStreams. The document provides code examples for implementing OAuth2 login flows, making API requests, storing access tokens, and rendering data with templates. It also demonstrates a sample app that retrieves a feed and allows posting new entries.
Good karma: UX Patterns and Unit Testing in Angular with KarmaExoLeaders.com
The document discusses unit testing in Angular with Karma. It provides examples of UX patterns in Angular like binding elements to variables, lists, and click handlers. It also covers what controllers and scopes are and examples of testing components in Angular like services, factories, and UI elements. Hands-on examples are provided for setting up a test environment and writing tests.
Ember.js is a JavaScript framework for building web applications. It provides conventions and architecture to make applications more organized and testable. Key aspects of Ember.js include Ember objects, computed properties, templates powered by Handlebars, routes for navigation, and a data modeling layer using Ember Data. Components are also used to build reusable isolated views. Ember follows a "data down, actions up" pattern where data flows from parent to child components and user actions bubble up through the components.
BlackBerry DevCon 2011 - PhoneGap and WebWorksmwbrooks
PhoneGap and BlackBerry WebWorks allow developers to create cross-platform mobile apps using web technologies like HTML, CSS, and JavaScript. The document discusses how these tools were used to build a nursing app, including overcoming challenges related to platform differences and limitations. Feature detection was used to handle quirks across platforms. Performance was improved by dispatching functions asynchronously on BlackBerry 5. The developer recommends alternative approaches like using Backbone.js, jQuery Mobile, Jasmine BDD, and pre-generated JSON files for future projects.
A presentation made for the NG-CONF Israel that took place in jun 2014 at Google TLV Campus (http://ng-conf.gdg.co.il/)
its an overview of how to use ngRoute and UI-Router in your app this slideshow contain a link for a working demo
"Angular.js Concepts in Depth" by Aleksandar SimovićJS Belgrade
Angular.js concepts are organized into modules, controllers, scopes, views, directives, filters, and providers. Core concepts include dependency injection which allows components to request services from Angular's injector, and change detection which checks data for changes by running equality checks over dependent data. Modules contain related code and are made up of controllers, filters, directives, services and other components.
This document provides an overview of Azure SignalR, which enables real-time functionality over HTTP without polling. It discusses how Azure SignalR works by establishing a connection between clients and the Azure SignalR service to send and receive messages. The document also covers when Azure SignalR should be used, the runtimes it supports, how to set up a serverless architecture with Azure Functions, and how billing works based on outbound messages.
The document provides instructions for building a basic space shooter game using JavaScript and canvas. It demonstrates how to load assets like images, handle input events from keyboard keys to control player movement, create enemy objects that move across the screen, detect collisions between lasers and enemies, and add game states to track lives and score. The game loop redraws the game objects on an interval to animate their movement. Event handling is implemented through an event emitter to avoid messy code. The final sections provide a demo of the moving game elements and lasers firing, along with tips for continuing to learn game development.
Programming a game involves several phases: setup, running the game, listening for user input and enemy movement, handling world events, and tracking state changes. It is like following a recipe by defining variables for data like eggs and sugar, and functions for actions like whisking and baking. JavaScript and Canvas allow drawing on a web page, like loading an image for a player ship and painting a background. The next step is adding movement to the space game.
This document discusses elements that make games engaging as well as mechanics that can be used to design games. A good game is amusing, fun, and challenging for the player. It provides a goal for the player to work towards, such as winning a race or collecting points, and introduces opponents, whether computer-controlled enemies or other human players. Common game mechanics include actions the player can take, characters like avatars and enemies, an interactive environment, and challenges like avoiding enemies or finding hidden areas. Examples discussed are classic games like Super Mario 3, Galaga, and Quake to illustrate different mechanics like movement, shooting, jumping, and collecting items or defeating bosses. The document encourages designing new games using a tool like MakeCode Arc
The document discusses infrastructure as code using ARM templates on Azure. ARM templates allow infrastructure to be defined in code and treated like application code in version control. Key points covered include:
- ARM templates are JSON files that define Azure resources and deployment parameters
- Templates support parameters, variables, functions and outputs to define flexible and repeatable deployments
- Common elements like resources, properties, and tags can be authored in templates
- Templates are deployed via tools like Powershell or Azure CLI to create the defined infrastructure
Svelte is a compiler that optimizes code by avoiding unnecessary updates. It allows building standalone components without dependencies on frameworks. Svelte compiles code to plain JavaScript that can run anywhere. Key features include bindings that sync state between components and templates, reusable components, and directives like if/else and each that control the template.
This document discusses open-source software (OSS) and provides examples of commonly used OSS tools and frameworks. It defines OSS as software with source code released under an open-source license allowing users to study, change and distribute the software. Examples of widely used OSS projects mentioned include RxJS, NestJS, Ngrx, AngularFire, Nx, and Ionic. The document also discusses how developers can contribute to OSS projects through code contributions, funding, or other support and the challenges faced by OSS maintainers.
Schematics allow developers to define rules that transform a file system tree representation. They provide a workflow tool for scaffolding new components and services as well as updating existing code. The Angular CLI uses schematics under the hood to provide its functionality. Developers can build their own schematics to customize workflows by defining rules that apply transformations to a tree representation of files.
This document provides an overview of design thinking. It discusses how design thinking is an iterative process that involves empathizing with users, defining problems from the user's perspective, ideating solutions, prototyping ideas, and testing prototypes. Rather than taking problems at face value, design thinking challenges assumptions to reframe problems in a human-centered way. It encourages exploring unknown aspects of problems and generating alternative solutions. The document provides examples of how well-known problems could be viewed more broadly and solved innovatively using a design thinking approach focused on user needs rather than predefined solutions.
This document discusses strategies for overcoming imposter syndrome as a developer. It recommends practicing coding through challenges, open source contributions, and side projects to build unconscious competence. Communication skills like writing and public speaking can help clarify thinking. Changing one's mindset to believe in their ability to learn and solve problems is important. Ultimately, developers must choose to spend hours practicing and deciding how great they want to become.
Vue and Vuex allow you to build interactive web applications. The document discusses Vue basics like creating components, passing data between components using props and events, and routing between multiple pages. It also covers more advanced topics such as validating component inputs, watching for data changes, and using route parameters and query strings.
NGRX provides tools for implementing Redux patterns in Angular applications. The key components are:
- The Store holds the single source of truth application state as plain JavaScript objects and uses reducers to immutable update state in response to actions.
- Actions describe state changes and are dispatched to the Store which passes them to reducers. Reducers pure functions that return new state.
- Selectors allow slices of state to be accessed.
- Additional libraries provide debugging with devtools, routing integration, side effect handling, and entity management functionality. Files can be organized by domain or feature module.
This document provides an overview of using Kendo UI components with Angular. It discusses why one might choose to use Kendo UI, describes some of the main component groups like buttons, charts, dropdowns, grids, layout, popup, dialog, date inputs and inputs. It also covers how to install and configure themes, and how to import, display and handle events of the different components. The document is intended as a guide for developers looking to get started with building applications using Kendo UI and Angular.
This document discusses the history of asynchronous programming and how reactive programming with RxJS addresses limitations of previous approaches. It covers callback hell with nested callbacks, promises, and async/await. RxJS introduces Observables that allow streaming and combining of asynchronous data over time. The document demonstrates building basic Observable and Observer classes as well as an operator. Reactive programming with RxJS makes asynchronous code more readable and addresses issues like cancellation and error handling.
This document provides an overview of building NativeScript applications with Angular. It covers setting up a NativeScript project with Angular, using components and bindings, routing, forms, HTTP requests, and testing. While there are some minor differences from web Angular, NativeScript aims to embrace the Angular framework and allow building truly native mobile apps using Angular concepts.
Template forms allow creating forms directly in the template using directives like ngModel. Reactive forms use FormBuilder to build forms programmatically and attach validators and value changes. Both approaches allow collecting and validating user input, and associating forms with models. Forms are a key part of many applications for user input and data collection.
This document provides an introduction to RxJS, a library for reactive programming using Observables. It discusses some of the key concepts in RxJS including Observables, operators, and recipes. Observables can be created from events, promises, arrays and other sources. Operators allow chaining transformations on Observables like map, filter, switchMap. RxJS is useful for complex asynchronous flows and is easier to test than promises using marble testing. Overall, RxJS enables rich composition of asynchronous code and cancellation of Observables.
1) Rxjs provides a paradigm for dealing with asynchronous operations in a synchronous way using observables. Observables allow representing push-based data streams and provide operators to compose and transform these streams.
2) Operators like map, filter, and switchMap allow manipulating observable streams and their values in various ways. Common patterns include cascading asynchronous calls, parallelizing multiple requests, and retrying or error handling of streams.
3) Schedulers allow bending time and virtual clocks, enabling testing asynchronous code by controlling when asynchronous operations complete. Marble testing uses descriptive patterns to visually test observable streams and operator behavior.
2. History
Developed in 2009, Misko Hevery Google, Adam Abrons at Brat Tech LLC
Abrons left enter Igor Minar, Vojita Jina
Google Web Toolkit was too damn slow to work with. Enter GetAngular
Sponsored by Google
Current version 1.4.1 , The are working on angular 2.0 as well using ecmascript 6
3. Your first app
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body ng-app>
{{ 2+2 }}
<script src="angular.js"></script>
</body>
</html>
ng-app
Creates an application context
5. Add a controller
<body ng-app="app">
<div ng-controller="personController">
<h1>{{ title }}</h1>
<fieldset>
{{ person.name }}
{{ person.address }}
</fieldset>
</div>
<script src="angular.js"></script>
</body>
angular
.module('app', [])
.controller('personController', function ($scope) {
$scope.title = "A person view";
$scope.person = {
name : 'John Doe',
address : 'Unknown'
}
});
Controller context
6. Interacting - the view
ng-click, calls a callback on your scope
ng-repeat loops out an array
on your scope
ng-model, creates a two-way binding
between view and controller
<body ng-app="app">
<div ng-controller="personController">
<h1>{{ title }}</h1>
<fieldset>
<p>
<input type="text" ng-model="person.name" placeholder="name" />
</p>
<p>
<input type="text" ng-model="person.address" placeholder="address" />
</p>
<p>
<input type="text" ng-model="person.age" />
</p>
</fieldset>
<button ng-click="save()">Save</button>
<ul ng-show="errors.length > 0">
<li ng-repeat="error in errors">
{{ error }}
</li>
</ul>
</div>
<script src="angular.js"></script>
ng-show, boolean expression that
shows or hides your element
7. Interacting – changing data
<fieldset>
<p>
<input type="text" ng-model="person.name" placeholder="name" />
</p>
<p>
<input type="text" ng-model="person.address" placeholder="address" />
</p>
<p>
<input type="text" ng-model="person.age" />
</p>
</fieldset>
angular
.module('app', [])
.controller('personController', function ($scope) {
$scope.title = "A person view";
$scope.person = {
name : 'John Doe',
address : 'Unknown',
age : 0
}
Change this
Change reflected here
8. Interacting – saving…
<button ng-click="save()">Save</button> angular
.module('app', [])
.controller('personController', function ($scope) {
$scope.title = "A person view";
$scope.person = {
name : 'John Doe',
address : 'Unknown',
age : 0
}
$scope.save = function (){
if (getErrors().length === 0) {
console.log('send data to backend');
} else {
console.log('has validation errors');
}
9. Interacting - boolean + loop
<ul ng-show="errors.length > 0">
<li ng-repeat="error in errors">
{{ error }}
</li>
</ul>
function getErrors(){
var errors = [];
if (person.name === '') {
errors.push('first name missing');
}
if (person.lastname === '') {
errors.push('last name missing');
}
if (person.age < 18) {
errors.push('must be 18 or over');
}
return errors;
}
$scope.errors = [];
}
10. What else can a module do
Factory
Service
Provider
Filter
Config – you wire up routing etc here..
Value - happens after config
Constant - happens first
11. Dependency injection
angular
.module('app')
.controller('ctrl', function($scope, personService, Product, constantValue){
})
Type the name of it and angular will look in its core for a definition and
Inject it
angular
.module('app')
.controller('ctrl',[
'$scope',
'personService',
'Product',
'constantValue',
function($scope, personService, Product, constantValue){
// do stuff
}])
Minification safe
12. Factory – acting as a service
- The factory is a method on the module
- Its a singleton
- You should return something from it
angular
.module('app', [])
.factory('mathFactory', function () {
return {
add : function (lhs, rhs) {
return lhs+ rhs
}
}
}) Returning an object literal
angular
.module('app', [])
.controller('personController', function ($scope, mathFactory) {
mathFactory.add(2,2) // outputs 4
}
13. Factory – acting as model factory
angular
.module('app', [])
.factory('User', function () {
function User(dto){
this.firstName = dto.firstname;
this.lastName = dto.lastname;
this.age = dto.age;
}
User.prototype.getFullName = function() {
this.firstname + " " + this.lastname;
}
User.prototype.canVote = function (){
return this.age > 18;
}
return User;
})
Constructor method angular
.module('app', [])
.factory('userService', function ($http, User) {
var getData = function (){
// get users from backend
var usersFromBackend = [];
var users = [];
usersFromBackend.forEach(function (userDto) {
users.push(new User(usersDto));
});
return users;
}
return {
getUsers : getData
};
});
14. Service
angular
.module('app')
.service('dateService', function () {
this.getHolidays = function () {
// code
};
this.getWorkingDays = function () {
// code
};
})
angular
.module('app')
.controller('anyController', function ($scope, dateService) {
$scope.dates = dateService.getHolidays();
});
15. Filter – formatting
1) Format data
$scope.val = 1140,123567
{{ val | number : 0 }}
// 1,140 thousand separator
{{ val | number : 4 }}
// 1,140.1236 rounded up and 4 decimals
1b) Format data – custom filter
angular
.module('app')
.filter('prefixed', function () {
return function (val) {
return "#" + val;
}
})
Usage
$scope.prefixThis = ’hello’;
<p>
{{ prefixThis | prefixed }}
</p>
// ’#hello’
16. Filtering
2) Select a subset from a list – non specific
{ { filter_expression | filter : expression : comparator} }
<input type="text" ng-model="filterByName" />
<div ng-repeat="user in users | filter:'filterByName'">
{{ user.name }}
</div>
<!-- will only look at 'name' -->
<input type="text" ng-model="search.name" />
<table >
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friendObj in friends | filter:search:strict">
<td>{{friendObj.name}}</td>
<td>{{friendObj.phone}}</td>
</tr>
</table>
2b) Select a subset from a list –specific
2c) orderBy filter
<div ng-repeat="item in items | orderBy: '+name' ">
{{item}}
</div>
<div ng-repeat="item in items | orderBy: scopeProperty ">
{{item}}
</div>
Filter by item.name
Filter by a property on the scope
+- sort order
24. Backend promise – resolve / reject
$q is used to create promises and also to resolve/ reject promises
function getData(value){
var deferred = $q.defer();
if (value > 5) {
deferred.resolve("higher than five");
} else {
deferred.reject("boo too low");
}
return deferred.promise;
}
function callData(){
getData(6).then(function (result) {
console.log(result); // returns 'higher than five'
});
getData(1).then(function (result) {
// never comes here
}, function (error) {
console.log(error); // returns 'boo too low'
});
}
25. Backend promise, wait for all
function longRunningService() {
var deferred = $q.defer();
$timeout(function () {
deferred.resolve('long');
}, 4000);
return deferred.promise;
}
function shortRunningService() {
var deferred = $q.defer();
$timeout(function () {
deferred.resolve('short');
}, 1000);
return deferred.promise;
}
function call() {
return $q.all([shortRunningService(), longRunningService()]).then(results) {
// 4 seconds later results[0] and results[1] populated
} ;
}
26. Backend promise, hiearchical call
function validateRequestIsAuthenticated() {
var deferred = $q.defer();
deferred.resolve('a');
return deferred.promise;
}
function validateParameters() {
var deferred = $q.defer();
deferred.resolve('b');
return deferred.promise;
}
function loginUser() {
var deferred = $q.defer();
deferred.resolve('c');
return deferred.promise;
}
function getProducts() {
var deferred = $q.defer();
deferred.resolve('d');
return deferred.promise;
}
function call() {
return validateRequestIsAuthenticated()
.then(getCustomer().then(function(customer){
getProductsByCustomer(customer.id)
}))
.then(loginUser)
.then(getProducts)
.then(function (products) {
return products;
}, function (error) {
// something failed with one of our calls
});
}
One place to handle
error from any of the
above
Calls in order
27. Interceptors
http interceptors can be applied to request and response and on success and error respectively
So when is a good time to use it?
- Handle all incoming error responses, route to error page
- All outgoing requests should have a custom header
And other things you can think of that should happen on a global level for all requests / responses
- Read data from cache if application seems to be offline
28. Interceptor – set a custom header on all
requests
.factory('authService', function() {
return {
isLoggedIn : function () {
return true;
},
token : 'aToken'
};
})
.factory('customHeaderInjector', function(authService) {
return {
request : function (config) {
if (authService.isLoggedIn()) {
config.headers['Authentication'] = authService.token;
}
return config;
}
}
})
30. Watch
When a scope property has change and you want to know about it
$scope.personName = 'Zlatan';
$scope.save = function(val){
$scope.personName = val;
}
$scope.$watch('personName', function(newValue, oldValue){
});
$scope.person = {
name : 'Zlatan',
age : 33
};
$scope.save = function(val){
$scope.person = val;
}
$scope.$watch('person', function(newValue, oldValue){
},true);
True, look at the whole object hierarchy
32. Events – two controllers talking
parent => child $scope.$broadcast(’kids – sit still in the car’, data)
child => parent $scope.$emit(’mommy – are we there yet’,data)
sibling => sibling $rootScope.$emit(’event’, data) listeners are other $rootScope.$on(’event’)
Madman $rootScope.$broadcast(’telling the whole world – the end is near, repent’,data)
Best!
33. Events – code example
.factory('eventService', function($rootScope) {
return {
publish : function (eventName, data) {
$rootScope.$emit(eventName, data);
},
subscribe : function (eventName, callback) {
$rootScope.$on(eventName, callback);
}
}
})
.controller('appController', function($scope, eventService){
$scope.send = function(){
eventService.publish('app_event',{ data : 'data from app controller' });
};
.controller('firstController', function($scope, eventService){
eventService.subscribe('app_event', function(event, data){
$scope.appMessage = data.data;
})
Publish to whoever listens to that eventHelper
Keep track on namespaces for events and be careful, don’t spam
36. Directives - intro
The main idea is to
- clean up html
and also to
- create reusable parts aka ”user controls”.
Directives can be applied on different levels
- as its own element
- as an attribute on an existing element, also called decorating directive
- on css level
- on a comment
I will be covering the two first ones Element + Attribute
37. Directives – most concepts
angular
.module('app')
.directive('someDirective', function () {
return {
restrict : 'E',
// E= element,A = attribute,C= css class, M = comment, what this directive can be applied to
replace : true, // whether to let template replace element tag or keep element tag
scope : true, // true = new scope that inherits, false = parent scope, {} = new + no inheritance
template : ’<h1>{{title}}</h1>', // or templateUrl
controller : function ($scope) { },
link : function (scope, element, attributes) { }
}
39. Directive - Info card
angular
.module('app')
.directive('infoCard', function () {
return {
restrict : 'E',
scope : false,
replace : true,
template : '<div>'+
'<h1>{ { title }}</h1>'+
'<p><input type="text" ng-model="info" /></p>'+
'</div>'
}
})
You can do this, but
Change one, change all!!
Probably not what you wanted
<div ng-app="app">
<div ng-controller="appController">
<info-card></info-card>
<info-card></info-card>
<info-card></info-card>
<div ng-view></div>
</div>
</div>
angular
.module('app')
.controller('appController', function ($scope) {
$scope.title = 'My Application';
$scope.content = '';
})
Content is from controller so it is shared
between all instances
40. Directive – a better info card
angular
.module('app')
.directive('infoCardImproved', function () {
return {
replace : true,
restrict : 'E',
template : '<div class="info-card-improved">' +
'<h2>{{title}}</h2>' +
'<p><input type="text" ng-model="text" /></p>'
+ '</div>',
scope : true,
controller : function ($scope) {
$scope.text = 'empty text';
$scope.title = 'infoCardImproved';
}
}
})
<div ng-app="app">
<div ng-controller="appController">
<info-card-improved></info-card-improved>
<info-card-improved></info-card-improved>
<info-card-improved></info-card-improved>
<div ng-view></div>
</div>
</div>
This works as intended
41. Directive , isolated scope
angular
.module('app')
.directive('isolatedDirectiveValue', function () {
return {
restrict : 'E',
replace : true,
scope : {
title : '@',
description : '@'
},
template : '<div><h2>{{title}}</h2><p>{{description}}</p></div>',
controller : function ($scope) {
}
}
});
The scope is isloated in that it points to an object
scope : {}
Instead of false/true
42. Directive, isolated binding types
An isolated scope has its own scope but it can also communicate with data being binded to it
scope : {
title : '@',
description : '@'
}
Binding to static value <directive-name title="a value" description="a description value" ></directive-name>
Binding to a scope property
scope : {
title : '=',
description : '=’
}
<directive-name title="scopeProperty" description="scopePropertyDesc"></directive-name>
scope : {
updated : ’&',
}
Binding to a scope callback <directive-name changed="onUpdatedCallback" ></directive-name>
43. Directive, isolated callback
angular
.module('app')
.directive('dayBrowser', function () {
return {
replace : true,
restrict : 'E',
scope : {
dayChanged : '&'
},
templateUrl : 'directives/dayBrowser/dayBrowser.html',
link : function (scope, element, attrs) {
scope.day = new Date();
function addDays(currentDate, days) {
var newDate = new Date(currentDate);
newDate.setDate(currentDate.getDate() + days);
return newDate;
} ;
scope.incrementDate = function (val) {
scope.day = addDays(scope.day, val);
scope.dayChanged({ date : scope.day, a : 1 });
};
}
};
});
Bind to callback with &
Create an object literal with a named property
<day-browser day-changed="changed(date, a)"></day-browser>
Signatur needs to match
date,a
44. Directive, child and parent directive
Typical scenarios are tab and tabitems, day vs calender
Parent need to talk to a child, and vice versa
<tabs>
<tab></tab>
<tab></tab>
<tab></tab>
</tabs>
Parent directive
Child directives
Behaviour :
Expand one tab, close the others,
like an accordion
45. Directive, the parent
angular
.module('app')
.directive('tabs', function () {
return {
restrict : 'E',
replace: true,
controller : function ($scope) {
var tabs = [];
this.addTab = function (tab) {
tabs.push(tab);
};
this.expand = function (tab) {
tabs.forEach(function (tab) {
tab.collapse = true;
});
$scope.$apply(function () {
tab.collapse = false;
});
};
}
};
});
Functions we want the child directives to call
WAIT, we are putting the functions on this, instead of $scope
Thats how angular wants it – deal with it
46. Directive, the child
angular
.module('app')
.directive('tab', function () {
return {
restrict : 'E',
replace: true,
scope : {
},
require: '^tabs',
template : '<div class="tab"><h1>tab header</h1><div ng-
hide="collapse" class="body">tab content</div></div>',
link : function (scope, element, attributes, tabs) {
scope.collapse = true;
tabs.addTab(scope);
element.on('click', function () {
var oldValue = scope.collapse;
scope.collapse = !oldValue;
if (!scope.collapse){
tabs.expand(scope);
}
});
}
}
});
Angular is walking the dom looking for the controller
47. Directives – decorative (attribute)
angular
.module('app')
.directive('expanderDirective', function() {
return {
link : function (scope, element, attributes) {
var bodyElem = element.find('.body');
var visibleBody = true;
element.on('click', function () {
scope.$apply(function () {
if (visibleBody) {
bodyElem.hide();
} else {
bodyElem.show();
}
visibleBody = !visibleBody;
});
});
}
}
});
<script src="bower_components/jquery/dist/jquery.js"></script>1
2 <script src="bower_components/angular/angular.js"></script>
<div expander-directive>
<div class="header">
header
</div>
<div class="body">
body text
</div>
</div>
Usage
Call $apply, when outside of angulars world
Reference jquery if you need
more power than jquery lite
50. Testing – setup config file
When you did karma init it created a config file.
files : {} // this is where you tell karma to find your application and your tests
frameworks: ['jasmine'] // for now it is jasmine could be qunit or something else
reporters: ['progress'] // this is where you specify things that can show you things like coverage
51. Testing – setup a test
1
2
3
Point to app and tests in config
Define test
Perform call
Assert4
files: [
'app/**/*.js*/',
'specs/**/*.js*/'
]
describe('given a calculator', function(){
var Calculator;
it('verify that addition works', function(){
var actual = Calculator.add(1,1)
expect().toBe(2);
});
52. Testing – setup an angular test
1
2
3
Import module and possible dependant modules
Import definition
Perform call
Assert4
files: [
'bower_components/angular/angular.js',
'bower_components/angular-mocks/angular-mocks.js',
'app/**/*.js',
'specs/**/*.js'
]
0 Point to 1) angular + angular-mocks, 2 ) to app 3) tests
//load module
beforeEach(module('services'));
//load definition
beforeEach(inject(function(_Calculator_) {
Calculator = _Calculator_;
}));
it('verify that addition works', function(){
var actual = Calculator.add(1,1);
expect(actual).toBe(2);
});
53. Testing – angular test with dependency
describe('given a user service', function(){
var UserService;
//load modules
beforeEach(module('models'));
beforeEach(module('services'));
//load definition
beforeEach(inject(function(_userService_) {
UserService = _userService_;
}));
it('test parse', function(){
});
})
angular
.module('services')
.factory('userService', function(User, $http){
var that = {};
that.doStuff = function(){
};
that.get = function(){
return $http.get('/users/1');
};
return that;
});
54. Testing with a $http / promise
You DON’T want to go against the real backend so use $httpBackend, built in mockObject that intercepts $http
$httpBackend.whenGET(’someUrl’).respond(fakeData)
Also because $http calls returns a promise we need to call $httpBackend.flush() to resolve promises
Assume we have the following scenario:
userController => userService.getUser() => $http.get(’/users/1’);
In a test
$httpBackend.respond({ name : ’Zlatan’ })
Mock response
55. Testing a controller and a promise
describe('given a UserController', function(){
var UserController,
$scope,
ctrl,
$httpMock;
//load modules
beforeEach(module('models'));
beforeEach(module('services'));
beforeEach(module('controllers'));
//load definition
beforeEach(inject(function($controller, $rootScope, $httpBackend){
$httpMock = $httpBackend;
$httpMock.expectGET('/users/1').respond({ name : 'Zlatan' });
$scope = $rootScope.$new();
ctrl = $controller('userController', { $scope: $scope });
}));
it('verify I can get a user', function(){
$scope.load();
$httpMock.flush();
expect($scope.user.name).toBe('Zlatan');
});
})
Instruct $http mock to intercept
Construct controller
Resolve promises
Needed to create a new scope
56. Testing - mocking
describe('given a mathService', function(){
var Service;
beforeEach(module('services'));
beforeEach(function(){
module(function($provide){
$provide.factory('Calculator', function (){
return {
add : function(){
return 1+1;
}
};
});
});
});
beforeEach(inject(function(_mathService_) {
Service = _mathService_;
}));
it('verify that mathService add works', function(){
expect(Service.add(2,2)).toBe(4);
})
})
angular
.module('services')
.factory('mathService', function(Calculator){
var that = {};
that.add = function(lhs,rhs){
return Calculator.add(lhs,rhs);
};
that.sub = function(lhs,rhs){
return Calculator.sub(lhs,rhs);
};
return that;
});
Calculator
is replaced,
with a mock
57. Lab, setup config, write a test
Install karma
Try creating a test, try creating a test for an angular application
58. Task runners grunt / gulp
What problem do they solve?
During development, what do you need
On change:
jshint
Unit test
For deploy, what do you need to do
Uglify, js
Minify js
Compress js, css, html
59. Gulp
4 apis
gulp.task , defines a task, with gulp your run tasks
gulp.src ,points out one or several files
gulp.dest, points out a destination
gulp.watch, watches files for changes, reacts on save and then performs what you instructed it
61. Gulp, first task
gulp.task('copy', function(){
return gulp
.src('./copyfromhere/*.txt')
.pipe(gulp.dest('./tohere/'));
});
From where and which files
Copy to destination dir, pipe is so that
we keep working on the same stream,
no temp files like grunt
gulp copy //to run
62. Gulp - dependencies
gulp.task('default',['thenme'],function(){
console.log('running default...');
})
gulp.task('thenme', ['mefirst'], function(){
console.log('then me');
});
gulp.task('mefirst', function(){
console.log('me first');
});
[’task’] dependency, this is run before
The specified task
So mefirst then thenme and lastly default
default task doesn’t need to be specified
just run
gulp
63. Gulp - Building a deploy task
- We want to create as small of a foot print as possible, one or a few js-files, uglified
For js
◦ Concatenate into one or a few js files
◦ For angular, run ng-min to ensure names are preserved on dependencies
◦ Uglify, i.e compress, remove whitespace etc..
For css,
◦ run preprocessors like sass/less
◦ Concatenate
◦ Uglify
64. Gulp – deploy task code
gulp.task('build',[], function(){
console.log('running build..');
return gulp
.src('./app/**/*.js')
.pipe(concat('all.js'))
.pipe(uglify())
.pipe(gulp.dest('./dest/'));
});
Concatenate
Uglify
Place in dest folder
Depending on how complex your app is
This task might grow if you have many modules
65. Gulp – Building a monitor task
Well before checking in code we want to know if
- unit tests are green
- no problems with hint/lint
For this we can use a watch task, watch is part of gulp api
66. Gulp – monitor task code
gulp.task('watch',function(){
gulp.watch(['app/**/*.js','test/**/*.js'], ['lint','test']);
});
gulp.task('test', function() {
gulp.src(testFiles)
.pipe(karma({
configFile: 'karma.conf.js'
}));
});
gulp.task('lint', function(){
console.log('linting...');
return gulp
.src(['./app/**/*.js','./test/**/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
Run tests
Run jshint
On file change (and save) run