angularjs workshop
TRANSCRIPT
© Copyright SELA Software & Education Labs, Ltd. | 14-18 Baruch Hirsch St., Bnei Brak, 51202 Israel | www.selagroup.com
SELA DEVELOPER PRACTICEMay 31st – June 4th, 2015
Ran WahleAngularJS – from 0 to 60
Agenda
IntroductionModules and dependency injectionData binding, controllers and scopesServicesFiltersDirectivesForm validationRouting
The Problem
As we add more and more JavaScript, our application is getting:
Harder to Maintain
Harder to Test
Harder to Understand
What Is AngularJS?
An MV* framework for developing CRUD style web applicationsDeveloped by GoogleWorks on all modern web browsersOpen source (MIT license)No external dependencies
Angular Building Blocks
ModuleModule
Module
Scope Controller ServiceTemplate
Filter Directive
Two-Way Binding
Dependency Injection
Routing
<!doctype html><html data-ng-app> <head> </head> <body> <input type="text" data-ng-model="name" /> {{name}} </body></html>
Your first AngularJS page
Module
Divide application into small pieces Can contain controllers, services, directives, etc.Can depend on other modulesOther modules can depend on it
//Creating a module
angular.module('yourModuleName', [ /*…dependencies…*/ ]);
//Accessing a module
angular.module('yourModuleName'); //Note: no dependencies array
Creating a module
Dependency Injection
Each angular application has an $injector serviceComponents are injected by the $injectorThere are several options for using dependency injection
One option removes the responsibility of locating the dependency from the component. The dependency is simply handed to the component.In Angular each application has an injector that is responsible for construction and lookup of dependencies
function SomeClass(greeter) { this.greeter = greeter;} SomeClass.prototype.doSomething = function(name) { this.greeter.greet(name);}
Dependency Injection cont.
Creating a component
angular.module('yourModuleName').service('serviceName', function() { //service’s code});
Creating an Angular component
Consuming the component
angular.module('yourModuleName') .controller('controllerName', ['serviceName', function(serviceName) { //controller’s code });
© Copyright SELA software & Education Labs Ltd. | 14-18 Baruch Hirsch St Bnei Brak, 51202 Israel | www.selagroup.com
Data binding
Controllers, scopes and views
AngularJS supports MV*- patterns
ViewsHTML
templates
ControllersJavaScript functions
Data Model
$scope
HTML templates
An HTML element with Angular-related attributesDeclarativeContains Angular-specific elements and attributesContains expressions evaluated against scope properties
<html> <head> </head> <body data-ng-app="myAppName"> <div data-ng-controller="myController"> <input data-ng-model="name" /> <button data-ng-click="greet()">Greet</button> </div> </body></html>
HTML template
Controller
A JavaScript constructor functionContains view related logicCan get and set data on the $scopeShouldn’t have any DOM related functionalitySets up the $scope initial stateAssociated with a template via the ng-controller directive
angular.module('myAppName') .controller('myController', ['$scope', function($scope) {
var greet = function() { alert('Hello ' + $scope.name); };
$scope.greet = greet;
}]);
Controller
$scope
The glue between the HTML template and the controllerHierarchical in the same way as HTMLHierarchy implemented using JavaScript prototypesThe root scope is represented by the $rootScope service
Services
Reusable singleton objectsCan be injected into controllers, filters, directives and other servicesCreated only when neededThere are many built-in services in AngularJS
angular.module('myApp') .service('myService', [/*…dependencies…*/, function(/*…dependencies…*/)
{ //service logic here this.someMethod = function() {}; }]);
angular.module('myApp') .controller('myController', ['myService', function(myService) { myService.someMetho(); }]);
Creating and using a service
Built-in services
$rootScope
$timeout
$location
$interval
$log
$compile
$rootElement
$parse
$window
$cacheFactory $animate
Ajax using $http
$http service is a built-in service in AngularJSUsed for communicating with the serverWraps XMLHttpRequestAutomatically serializes/deserializes JSONSupports request and response transformationSupports request and response interception
$http.get('url') .success(function(response) { //handle the server's response }) .error(function(errorResponse) { //handle the server's error response });
$http.post('url', requestBody);$http.put('url', requestBody);$http.delete('url', requestBody);
Using $http
$http({ url: 'url', method: 'get', //or 'put', 'post', 'delete' params: {…}, //for get requests data: {…}, //for put or post requests}).success(…).error(…).finally(…);
Using $http (Cont)
The $resource Service
An abstraction on top of the $http service for interaction with RESTful web servicesDepends on the ngResource module and requires the inclusion of the angular-resource.js scriptReceives a parameterized URL, with optional default valuesReturns an object with convenient methods (get, query, $save, $delete, …)Custom actions can be configured as well
Using the $resource serviceangular.module('resourceDemo', ['ngResource']) .controller('questionsCtrl', function($scope) {
var baseUrl = '/api/v1.0/questions/:id'; var Questions = $resource(baseUrl, {id: '@id'});
$scope.loadQuestions = function() { $scope.questions = Questions.query(); };
$scope.removeQuestion = function(question) { question.$remove(); };
});
Filters
Formats the value of an expression for display to the user
{{ expression | filter }}{{ 10 | currency }} will display 10$
May have arguments{{ price | number:2 }}
Chainable
angular.module('myModule') .filter('digitToText', function() {
var digitToText = [ 'zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine' ];
return function(digit) { return digitToText[digit]; };
});
Create a custom filter
The form directive
Aggregates the state of all its input elementsSets CSS classes according to the stateThe default form action is automatically ignoredAvailable to the scope as a property with the name of the form
Contained input elements are also available by their names, as sub-properties of the form property
The form directive
Creates a formControllerThe formController aggregates the state of all form controlsThe formController is available to the current scope by its nameTo submit the form using Ajax, respond to ng-submit or ng-click
Built-in validation directives
Angular provides the following validation directives:required – Checks that the field has a valuemin – Checks that the field value is greater than the given valuemax – Checks that the field value is lower than the given valueminlength – Checks that the field value is longer than the given valuemaxlength – Checks that the field value is shorter than the given value pattern – Checks that the field value matches the given regular expression
All of the above directives set a validation error identified by their name when the condition is not met
The ngModel directive
Provides a two way data binding between the input element and the modelProvides automatic validation for common HTML5 input types (checkbox, email, number, text, url)Tracks the control’s stateSets CSS classes according to the state
Note the usage of the novalidate attribute to disable the browser’s built-in validation
<form name="form" novalidate> <div> <input type="text" name="title" ng-model="question.title" required /> </div> <div> <textarea name="content" ng-model="question.content" required> </textarea> </div> <button ng-click="addQuestion(question)”> Submit </button></form>
Using the form and ngModel directives
Directives
Custom HTML elements, attributes, classes and comments that are recognized by AngularEssentially extend the existing HTML vocabulary
Creating new elementsAdding behavior to existing elements
Most of the things we’ve seen so far are built-in directives (ng-app, ng-controller, ng-repeat, ng-model, required, …)
Creating custom directives
Directives are registered on modules, with the module.directive function, which takes the directive name and a factory functionThe factory function should return a directive definition object (discussed in the following slides)It’s a best practice to prefix custom directives to prevent collision with other 3rd party directives, or a future standard
The following code demonstrates the definition of a new directive, named myDirectiveNote that this is a only a skeleton with an empty directive definition object. We’ll fill this object with properties in the following slides.
myModule.directive('myDirective', function() { return { };});
Creating a custom directive
Create a custom directiveThe object retuned can have the following properties:• link: a function that is called during the linking phase• template: an HTML template for the directive• templateUrl: a rooted path to an HTML template file• require: specifies a dependency on another
directive• transclude: determines whether child elements
should be included in the template• controller: used to share behavior and
communicate with other directives
Routing in Single Page Applications
Unlike traditional web sites, in SPAs, the responsibility for rendering the view is on the client sideWe do, however, want to give the user the same features they are used to, such as:
The browser’s navigation buttonsThe address bar for navigationThe ability to bookmark specific pages
How can we change the address bar without causing the browser to issue a new request?
The $location service
An abstraction on top of the window.location objectSynchronized with the browser address bar and allows to watch or manipulate the URLSeamless integration with the HTML5 History API. Links are automatically rewritten to reflect the supported mode.
<a href="/page1?id=123">link</a>
/index.html#/page1?id=123
/page1?id=123
The ui.router module
Angular comes with a built-in router named ngRouteBut most projects use the 3rd party AngularUI Router
The AngularUI Router is packaged in its own module, named ui.routerTo use the router, perform the following steps:
Install and reference the angular-ui-router.js script in the HTMLAdd the ui.router module as a dependency to your module
Routes are registered in the module’s config function, by calling the $stateProvider.state method with a state name and a route objectA default route can be registered with the $routeProvider.otherwise methodThe contents of the route object are discussed in the following slides
myModule.config(function($stateProvider) { $stateProvider("page1", {url: '/page1', …}) .state("page2", {…}) .state("page3", {…})});
Route registration
The 3rd party uiView directive marks the place in which the new route’s template should be renderedCan be used as an element, or as an attribute on any element
<body ng-app="myModule"> <div> <ul> <li><a ui-sref="page1">Page 1</a></li> <li><a ui-sref="page2">Page 2</a></li> </ul> </div> <div ui-view /></body>
The uiView directive
Modules and dependency injectionData binding, controllers and scopesServicesFiltersForm validationDirectivesRouting
Email: [email protected]
Summary