This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Jscript Hotspots – AngularJS,Angular2,
ReactJS, Node.js & more
כץויריבשיבקיאיר
Agenda
• Introduction– Web Development Trends
– Modern Web App Architecture
– Tools & Frameworks Overview
• Deep Dive into selected JavaScript Frameworks– Knockout
Tell us your email.</span><span ng-show="form.uEmail.$error.email">
This is not a valid email.</span></span>
FormController Properties Sample
NgModelController Properties Sample
NgModelController
Provides API for the ng-model directive.
The controller contains services for:
➢ Data-binding
➢ Validation
➢ CSS update
➢ Value formatting and parsing
NgModelController
View(Form)
Model
NgModelController
➢ $render()➢ $setValidity()➢ $setViewValue()
➢ $viewValue➢ $modelValue
➢ $parsers➢ $formatters
➢ $error➢ $pristine➢ $dirty➢ $valid➢ $invalid
Custom Validation Flow▪ The validation can occur in two
places:
▪ Model → View update.
▪ View → Model update.
View Model$formatters$setValidity
$parsers $setValidity
Custom Validation ( View to Model )
app.directive('smartFloat', function () {return {
require: 'ngModel',link: function (scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift( function (viewValue) {if ( FLOAT_REGEXP.test(viewValue) ) {
// it is validctrl.$setValidity('float', true);return parseFloat(viewValue.replace(',', '.'));
} else {// it is invalid, return undefined (no model update)ctrl.$setValidity('float', false);return undefined;
}});
}};
});
<div>Length (float):<input type="text" ng-model="length" name="length" smart-float />{{length}}<br /><span ng-show="form.length.$error.float">This is not a valid float number!</span>
// load init value from DOMctrl.$setViewValue(elm.html());
}};
});
<div ng-model="content" title="Click to edit" contentEditable="true" >Some</div><pre>model = {{content}}</pre>
Custom Directive Validation
Agenda
▪ Service Overview
Angular Services
Custom Services
Angular ServicesAngular services are singletons that carry out specific tasks.
All services in Angular are instantiated lazily.
There are three functions for creating generic services, with different levels of complexity and ability:➢ Service
➢ Factory
➢ Provider
$http ServiceThe AngularJS XHR API follows what is commonly known as the Promise interface.
➢ Use the then method to register callbacks, and these callbacks will receive a single argument – an object representing the response. $http({ method: 'GET', url: '/someUrl' }).success(function (data, status, headers, config) {
// this callback will be called asynchronously// when the response is available
Setting HTTP HeadersThe $http service will automatically add certain HTTP headers to all requests.
These defaults can be fully configured by accessing the $httpProvider.defaults.headers configuration object.angular.module('MyApp', []).config(function ($httpProvider) {
// Remove the default AngularJS X-Request-With headerdelete $httpProvider.defaults.headers.common['X-Requested-With'];// Set DO NOT TRACK for all Get requests$httpProvider.defaults.headers.get['DNT'] = '1';
});
$http.get('api/user', {// Set the Authorization header. In an actual app, you would // get the auth token from a service.headers: {'Authorization': 'Basic Qzsda231231'},params: {id: 5}
}).success(function() { // Handle success });
Transforming Requests & ResponsesAngularJS applies some basic transformations on all requests and responses made through its $http service.➢ Request transformations:
➢ If the data property of the request configuration object contains an object, serialize it into JSON format.
➢ Response transformations:➢ If XSRF prefix is detected, strip it ➢ If JSON response is detected, deserialize it using a JSON parser.
var module = angular.module('myApp');
module.config(function ($httpProvider) {$httpProvider.defaults.transformRequest = function (data) {
// We are using jQuery’s param method to convert our// JSON data into the string formreturn $.param(data);
};});
$http CachingTo enable caching, set the configuration property cache to true.
When the cache is enabled, $http stores the response from the server in local cache.
➢ Next time the response is served from the cache without sending a request to the server.
$http.get('http://server/myapi', {cache: true
}).success(function() { // Handle success });
Response interceptorsThe interceptors are service factories that are registered with the $httpProvider by adding them to the $httpProvider.responseInterceptors array.// register the interceptor as a service$provide.factory('myHttpInterceptor', function ($q, dependency1, dependency2) {
return function (promise) {return promise.then(function (response) { // do something on success return response;
}, function (response) {
// do something on errorif (canRecover(response)) { return responseOrNewPromise }return $q.reject(response);
paramDefaults(optional) – {Object=}➢ Each key value in the parameter object is first bound to url template
if present and then any excess keys are appended to the url search query after the ?.
➢ Given a template /path/:verb and parameter {verb:'greet', salutation:'Hello'} results in URL /path/greet ? salutation=Hello.
actions(optional) – {Object.<Object>=}➢ Hash with declaration of custom action that should extend the default
set of resource actions.{ action1: {method:?, params:?, isArray:?}, action2: {method:?, params:?, isArray:?}, ...}
➢ action – {string} – The name of action.
➢ Method – GET,POST,DELETE & JSONP
➢ Params - Optional set of pre-bound parameters for this action.
➢ isArray - bool
$resource Returns Values{Object} – A resource "class" object with methods for the default set of resource actions optionally extended with custom actions. The default set contains these actions:
var User = $resource('/user/:userId', { userId: '@id' });var user = User.get({ userId: 123 }, function () {
user.abc = true;user.$save();
});
$q ServiceA promise/deferred implementation inspired by Kris Kowal's Q.
“Interface for interacting with an object that represents the result of an action that is performed asynchronously, and may or may not be finished at any given point in time.”
step1(function (val1) {step2(value1, function (val2) {step3(value2, function (val3) {step4(value3, function (val4) {// Do something with val4
});});
});});
Q.fcall(step1).then(step2).then(step3).then(step4).then(function (val4) {// Do something with val4
}, function (error) {// Handle any error from step1 // through step4
The purpose of the deferred object is to expose the associated Promise instance as well as APIs that can be used for signalingthe successful or unsuccessful completion of the task.
A new instance of deferred is constructed by calling $q.defer().
resolve(value)
reject(reson)
The Promise API
▪ A new promise instance is created when a deferred instance is created and can be retrieved by calling deferred.promise.
▪ The promise object allow for interested parties to get access to the result of the deferred task when it completes.➢ then(successCallback, errorCallback)
Write Async Methodfunction asyncGreet(name) {
var deferred = $q.defer();setTimeout(function () {
scope.$apply(function () {if (okToGreet(name)) {
deferred.resolve('Hello, ' + name + '!');} else {deferred.reject('Greeting'+name+'is not
allowed.');}
});}, 1000);return deferred.promise;
}asyncGreet('Robin Hood').then( function (greeting) {
alert('Success: ' + greeting);}, function (reason) {
alert('Failed: ' + reason);});
Registering Servicesyou can register the service with the module either via the Module api or by using the $provide service in the module configuration function.
var myModule = angular.module('myModule', []);myModule.factory('serviceId', function () {
var shinyNewServiceInstance;//factory function body that constructs shinyNewServiceInstancereturn shinyNewServiceInstance;
});
angular.module('myModule', [], function ($provide) {$provide.factory('serviceId', function () {
var shinyNewServiceInstance;//factory function body that constructs shinyNewServiceInstancereturn shinyNewServiceInstance;
});});
Option I
Option II
$provideThe providers are the factories for the instance.
The providers share the same name as the instance they create with Provider suffixed to them.
A provider is an object with a $get() method.
➢ The injector calls the $get method to create a new instance of a service.
$provide Methodsservice(name, constructor)➢ you will be provided the actual function
reference passed to module.service.
factory(name, $getFn)➢ you will be provided the value that is returned by
invoking the function reference passed to module.factory.
provider(name, provider)➢ you will be provided the value that is returned by
invoking the $get method of the function reference passed to module.provider.
Angular $provide (Custom Service)
Dependency Injection ($inject)Each Angular application has an injector.
The injector is a service locator that is responsible for construction and lookup of dependencies.