Introduction to AngularJS
Workshop
Pete Bacon Darwin
AngularJS 1.x Team Lead
Get the slides
FoodMe App
Get the code
clone using git
git clone https://github.com/petebacondarwin/foodme-intro
or download zip file
https://github.com/petebacondarwin/foodme-intro/archive/master.zip
or copy from USB stick
AngularJS Basics
Directives
- Add behaviour to HTML
- ng-app - defines your Angular App
Scope
- Scope provides the data to the view
Data Binding
- {{ ... }} interpolation
- ng-model two-way binding
Step 1
Add Angular and basic bindings to the page:
- Load angular.js
- Add `ng-app` directive
- bind inputs to models with `ng-model` directive
- display models with `{{ ... }}` interpolation bindings
More directives
-
ng-show / ng-hide
- ng-click
Step 2
Show and hide parts of the page dynamically
- Show the form if `deliveryFormVisible`, using `ng-show`
- Hide the delivery info if`deliveryFormVisible`, using `ng-hide`
- Change `deliveryFormVisible`, using `ng-click`
Angular Building Blocks
- Modules - define components
- Controllers - provide logic for a view
- Services - singleton helper objects and functions
Step 3
Move the deliveryForm behaviour into a Controller
- create an `app` module and a `AppController` controller in `app.js`
- load the `app.js` file in the index.html page
- initialize the controller with a `deliveryFormVisible` property
- add `showDeliveryForm()` and `hideDeliveryForm()` methods to the `AppController`
- connect the `AppController` to the view using `ng-controller`
Scope Hierarchy
- There is more than one scope
- $root scope
- child scope 1
- grandchild scope
- child scope 2
- child scope 1
- Useful for structural directives
- ng-repeat
- ng-if
Step 4
Add a list of restaurants to choose from
- Initialize a mock list of restaurants on the scope in the `AppController`
- Bind the template to the list of restaurants using `ng-repeat` directive
Filters
Simple functions that modify bindings
Use the pipe | symbol in an expression to apply
{{ name | uppercase }}
Step 5
Implement sorting of the restaurant list
- Initialize `sortProperty` and `sortDirection` in the controller for sorting columns
- Add a `orderBy` filter to the `ng-repeat` using these properties
Step 5 - cont.
Implement sorting of the restaurant list
- Create methods in the controller, `sortBy(property)` and `getSortClass(property)`
- Convert the table headings to clickable anchors with `ng-click="app.sortBy('name')"` directives
- Display sort direction up/down markers using `ng-class="app.getSortClass('name')"` directives
Step 6
Create custom filter to display nicer price and rating values
- Create a custom `rating` filter in the `app` module
- Use the filter in the price and rating fields
Form Validation
Angular provides sophisticated declarative validation
- A named form gets attached to the scope
- Forms contain validation information
- Directives on input elements control validation
- Use ngMessages to display error messages
Step 7
Add validation to delivery form
- Give the form a name (`app.deliveryForm`)
- Give the inputs names (`userName`, `userAddress`)
- Add `required` and `ng-minlength="..."` validators
- Update CSS classes when the inputs are invalid
- Load the `../js/angular-messages.js` file
- Add the `ngMessages` modules as a dependency of our `app` module
- Use `ng-messages` directive to show error messages
Services
Well Defined Singleton Objects/Functions
- Defined on an AngularJS module
- Can be injected into components such as controllers, filters, directives and other services
- You specify a "recipe" for creating the service:
- value - simply register the service instance
- factory - register a function that will return the service instance
- service - register a class/type that will be instantiated
LocalStorageBinding
Step 8
Persist the delivery info in the local storage
- Create a `localStorage' service to wrap the browser's `localStorage` object
- Create a `localStorageBinding` service that connects a property on the scope to the `localStorage`
- Load the new `localStorage.js` file
- Add the new `localStorage` module as a dependency to our `app` module
- Bind the `user` object to the `localStorage` using the `localStorageBinding` service
Cross Origin Requests
- Browser Security Feature
- Can only make HTTP requests to your own origin
- Possible Solutions
- Server Proxy
- JSONP
- CORS
Step 9
Load the restaurant data from a server
(remote using CORS)
- Add the `$http` dependency to the `AppController`
- Replace the static data with a call to get the restaurant data from a remote server:
(https://foodme.firebaseio.com/.json)
Step 9 cont.
Load the restaurant data from a server
(hosting app and data locally)
- Install a local webserver
- Start the server in the root of the project
- Browse to the application via this server: `http://localhost:8080/step-09`
- Get the restaurant data from the local server
('../shared/data/restaurants.json')
Step 10
Filter the restaurants by price and rating
- Add a new form to the left of the restaurant list
- Initialize the filters to `null`
- Watch the price and rating values and create a filteredRestaurants list accordingly
- Change the `ng-repeat` directive to use the `app.filteredRestaurants`
Step 11
Display the number of filtered restaurants
- Add a binding to the length of the `filteredRestaurants` collection using `ngMessageFormat` and ICU syntax
Directives
Provide reusable visual components and low level interaction with the DOM
Step 12
Add a cool rating directive for use in filtering
- Create a new file `rating.js` containing a `rating` module
- Load the `rating.js` file into the app
- Add the `rating` module as a dependency of our `app` module
- Define a `fmRating` directive in the `rating` module
- Use this directive in the Filter Restaurants form instead of the simple text input boxes
Thanks!
Keep in touch: pete@bacondarwin.com
Find out more: https://doc.angularjs.org
Get involved: http://angularconnect.com
Introduction to AngularJS 2015
By Pete Bacon Darwin
Introduction to AngularJS 2015
- 2,580