19
Himanshu Khara Product Development Sr. Manager A Modern Javascript MVC Super Framework

Clarice Technologies - Introduction to Angular JS

Embed Size (px)

DESCRIPTION

Clarice Technologies www.claricetechnologies.com Product Development Services Company specializing in Integrated User Experience Design and Technology Development.

Citation preview

Page 1: Clarice Technologies - Introduction to Angular JS

Himanshu Khara Product Development Sr. Manager

A Modern Javascript MVC SuperFramework

Page 2: Clarice Technologies - Introduction to Angular JS

What Do Web Developers Need?

FROM THE ARCHITECT

• Scalability

• Maintainability

• Modular nature

• Cleanliness of Implementation

• Guidance

FROM THE APPLICATION

• Light-weight

• Performance

• Consistent/Uniform

• Usable

FROM THE TECHNOLOGY STACK

• Easy to Use

• Easy to test

• Tooling Support

• Standards-driven

FROM THE DEVELOPMENT PROCESS

• Quicker turn-around time

• Predictable Velocity

Page 3: Clarice Technologies - Introduction to Angular JS

Available Modern Javascript MVC Frameworks

CLIENT SIDE

• BackboneJS

• Spine - KnockoutJS

• KnockbackJS

• Ember.js

• AngularJS

• JavascriptMVC

• Sencha / ExtJS

References- http://backbonejs.org http://spinejs.com http://knockoutjs.com/ http://kmalakoff.github.com/knockback/index.html

http://emberjs.com http://angularjs.org/ http://javascriptmvc.com http://www.sencha.com http://meteor.com/

http://batmanjs.org http://derbyjs.org

CLIENT – SERVER – HYBRID

• MeteorJS

• Batman

• DerbyJS

Page 4: Clarice Technologies - Introduction to Angular JS

What is AngularJS?

Ang-who-lar?

Complete client-side JS framework solution

• Opinionated; but very flexible at the same time

• Higher-level abstraction

Open source; Developed by Google

• 3 years in development ; 1.0 released in June 2012 (current version - 1.0.4-bewildering-hair / 1.1.2-tofu-animation)

• Used in Google production projects

• Growing developer community

Decent (growing) API documentation, Tutorials & Development guides• http://builtwith.angularjs.org/

Support for all modern browsers & IE7 and above (using shims)

Page 5: Clarice Technologies - Introduction to Angular JS

Real World Users

AngularJS is used for many platforms and domains

• Used for many platforms and domains

• DoubleClick digital marketing manager by Google

• Google Places

• YouTube application on PS3

• Tetractis - Olympics 2012 real-time data

• SCamp - SoundCloud Playlist Manager

• GoodFilms.com website

• FolderChute - Pipeline for many cloud-storage services

• Provok.in - Crowd-enabled "affirmation" portal

References- http://places.google.com/ http://builtwith.angularjs.org/ https://github.com/angular/angular.js/wiki/Projects-using-AngularJS

Page 6: Clarice Technologies - Introduction to Angular JS

In-depth study of AngularJS

VIEWS PURELY <DECLARATIVE/>

• HTML "compiler" teaches old HTML new tricks

• Readable, expressive, easy-to-understand

• Great templating engine

2-WAY BINDING MODELS & VIEWS

• 2-way automatic updation of models & views

• Eliminates most DOM manipulation

MODELS AS PLAIN JAVASCRIPT OBJECTS

• Free from unnecessary boilerplate

• Reusable, extensible, testable

CONTROLLERS FOR BEHAVIOR

• Encapsulate logically related functionality on a page

• Cleanly separate out and add behavior to models

• Standard JS classes - no boilerplate

SERVICES

• Shared functionality across controllers

• $ Resource service based on Promise spec

• Allows synchronous assignment for async returns

• Support for REST, extensible to other paradigms

DEPENDENCY INJECTION

• Keeps parts of the app unaware of each other

• The DI runtime wires everything together

• Results in modular, easily testable code

Page 7: Clarice Technologies - Introduction to Angular JS

In-depth study of AngularJS

DIRECTIVES

• Easily create reusable HTML components

• Encapsulate markup, behavior and style

• Can be used as custom tags, attrs or comments

TESTABILITY

• Built with ease of unit testing in mind

• Well-separated concerns result in testable code

• Integrates very well with Jasmine

• Bundled scenario runner

OUTPUT FILTERS

• In-built routing perfect for single-page apps

• Deep-linking support

INTEROPERABILITY

• No hard dependencies; works well with most JS libs

• Can use any

PAGE NAVIGATION

• In-built routing perfect for single-page apps

• Deep-linking support

OUT-OF-THE-BOX GOODNESS

• Directives

• Reusable filters for clean output formatting

• XHR-wrapping services for ease of integration

• Validators for all basic HTML input types

• Basic localization support

• Mocks support for better testability Watch out!- Traditional web app concepts turned inside-out

- Dependency Injection can warp your mind initially

Page 8: Clarice Technologies - Introduction to Angular JS

Code Samples

Is this better than what we have?

Basic MV* pattern

• Templatized Views

• Lightweight Controllers (no DOM)

• Unintrusive Model definition

Directives

• Reusable components

• All DOM manipulation goes here

• Awesome !

Output Filters

Page Navigation & Routing

Page 9: Clarice Technologies - Introduction to Angular JS

Examples

Basic AngularJS example

<input ng-model="greeting" placeholder="Say hello to someone.." />

<h2 ng-init="greeting = 'World'">Hello {{greeting}} !!</h2>

Basic AngularJS example

function GreetingController($scope) {

$scope.greeting = 'World';

}

<div ng-controller="GreetingController">

<input ng-model="greeting" placeholder="Say hello to someone.." />

<h2>In English - Hello {{greeting}} !!</h2>

<h2>In French - Bonjour {{greeting}} !!</h2>

</div>

Page 10: Clarice Technologies - Introduction to Angular JS

Examples

Something more than “Hello World!”

function Tweet(props) { // MODEL DEFINITION Entity.call(this); // Activity may be a subclass angular.extend(this, props); // { isPrivate(), content, author, time }}

function TwitterFeedController($scope, Twitter) { // CONTROLLER / VIEWMODEL $scope.tweets = Twitter.get(...); // [<Tweet>] .. model $scope.postTweet = function () { TwitterService.submitTweet($scope.shoutText); };}

<div ng-controller="TwitterFeedController"> // VIEW <div class="input-append shout-out"> <input ng-model="shoutText" placeholder="What's on your mind?" /> <button ng-click="postTweet()">Post</button> </div> <ul> <li ng-repeat="tweet in tweets" ng-hide="tweet.isPrivate()"> <a>{{tweet.content}} by {{tweet.author}} at {{tweet.time | dateFormat}}</a> </li> </ul></div>

Page 11: Clarice Technologies - Introduction to Angular JS

Examples

Modularization

angular.module('social-api', [ ]) .service('Social', ['Twitter', function ($twitter) { return { twitter: Twitter, facebook: Facebook }; }]) .service('Twitter', ['$http', '$q', function($http, $q) { return { iterate: function (searchTerm, lastID) { if (!searchTerm) { return $q.defer().resolve([]); } var url = 'https://api.twitter.com/1.1/search/tweets.json' + '?&rpp=100&include_entities=true&result_type=mixed' + '&callback=JSON_CALLBACK', params = '&q=' + searchTerm + (lastID ? '&since_id='+lastID : ''); return $http.jsonp( url + params ) .then( function(response) { var data = response.data; return { items : data.results, refreshURL : data.refresh_url, query : data.query }; }); } };

}]);

angular.module('my-social-app', ['social-api']) // using the Social Module

Page 12: Clarice Technologies - Introduction to Angular JS

Examples

Directives & Filters – Part 1

angular.module('i18n-lib') .service('I18N', ['$http', 'GoogleTranslate', function ($http, GoogleTranslate) { return { get: function (key, parameters) { // fetch the string value from the language files // find out currently selected language (from session maybe) // replace argument-placeholders with parameters // return translated string } }; }])

// a simple internationalization service

Page 13: Clarice Technologies - Introduction to Angular JS

Examples

Directives & Filters – Part 2

angular.module('i18n-lib') .directive('i18n', ['$filter', 'I18N', function ($filter, I18N) { return { restrict: 'E', scope: { key: '@' }, link: function (scope, element, attrs) { var languageString = I18N.get(attrs['key']), ret, token, tokens, tokenVal, $scope = scope.$parent;

scope.$watch(replace);

function replace() { // mojo ! // GET the i18n-key and parameters (if any) // Ask I18N service to translate key (provide parameters if any) // render the translated string into the element element.html(I18n.get(...)); } } }; }])

.filter('i18n', ['I18N', function (I18N) { return function (key) { return I18N.get(key); }; }])

Page 14: Clarice Technologies - Introduction to Angular JS

Examples

Directives & Filters – Part 2 contd…

<h1>{{'hello_world' | i18n}}</h1><i18n key="hello" greetee="World"></i18n><i18n key="hello" greetee="Robert"></i18n>// where language files look like - // en-us.langhello_world = Hello Worldhello = Hello {greetee}// fr.langhello_world = Bonjour tout le mondehello = Bonjour {greetee}// de.langhello_world = Hallo Welthello = Hallo {greetee}

angular.module('my-social-app', ['social-api']) // using the Social Module

Page 15: Clarice Technologies - Introduction to Angular JS

Examples

Directives & Filters – Part 3

<h1>{{'hello_world' | i18n}}</h1><i18n key="hello" greetee="World"></i18n><i18n key="hello" greetee="Robert"></i18n>

// where language files look like –

// en-us.langhello_world = Hello Worldhello = Hello {greetee}// fr.langhello_world = Bonjour tout le mondehello = Bonjour {greetee}// de.langhello_world = Hallo Welthello = Hallo {greetee}

Page 16: Clarice Technologies - Introduction to Angular JS

Examples

Page definition & routing

// define parameterized URLs for routes$routeProvider .when('vote?d=:dName&eid=:dId!:type!:eId&q=:eName', { templateUrl: 'partials/challenge-voting.html', controller: ChallengeVotingController });

// Now, for /#vote?d=spigit-com&eid=1!challenge!2112&q=Whats-up

// all route arguments auto-injected into the controllerfunction AccountPageController($scope, $routeParams) { $routeParams == {

dName: 'spigit-com', dId: 1,type: 'challenge', eId: 2112, q: 'Whats-up'

}}

$routeProvider.html5Mode = true; // enables HTML5 pushState// all URLs seamlessly convert to - (no "#")http://.../vote?d=spigit-com&eid=1!challenge!2112&q=Whats-up

• “Pages" can be defined as external partials

• Streamlined routing; plugs in controller beautifully

• Parameterized URLs result in correct routing and readily available params within the controller

• Supports HTML5 History API (cleaner URLs)

Page 17: Clarice Technologies - Introduction to Angular JS

Examples

Model definition

function Tweet(props) { Entity.call(this); // Activity may be a subclass angular.extend(this, props); // { isPrivate(), content, author, time }}

function TwitterFeedController($scope, Twitter) { $scope.tweets = Twitter.get(...); // [<Tweet>] $scope.postTweet = function () { TwitterService.submitTweet($scope.shoutText); };}

<div ng-controller="TwitterFeedController"> <div class="input-append shout-out"> <input ng-model="shoutText" placeholder="What's on your mind?" /> <button ng-click="postTweet()">Post</button> </div> <ul> <li ng-repeat="tweet in tweets" ng-hide="tweet.isPrivate()"> <a>{{tweet.content}} by {{tweet.author}} at {{tweet.time | dateFormat}}</a> </li> </ul></div>

Page 18: Clarice Technologies - Introduction to Angular JS

Examples

Modularization

angular.module(social-api', [ ]) .service('Social', ['Twitter', function ($twitter) { return { twitter: Twitter, facebook: Facebook }; }])

.service('Twitter', ['$http', '$q', function($http, $q) {return {

iterate: function (searchTerm, lastID) { if (!searchTerm) { return $q.defer().resolve([]); } var url = 'https://api.twitter.com/1.1/search/tweets.json' + '?&rpp=100&include_entities=true&result_type=mixed' + '&callback=JSON_CALLBACK',

params = '&q=' + searchTerm + (lastID ? '&since_id='+lastID : '');

return $http.jsonp( url + params )

.then( function(response) { var data = response.data;

return {

items : data.results,

refreshURL : data.refresh_url,

query : data.query};

});}

};

}])

Page 19: Clarice Technologies - Introduction to Angular JS

Clarice Technologies

For more information : www.ClariceTechnologies.com+91.20.4078.9520info@claricetechnologies.com

Pune | Bangalore | USA