Introduction to Angular JS
Upcoming SlideShare
Loading in...5

Introduction to Angular JS



This presentation is an effort to combine all the cool features present in Angular and provide a basic idea about how it would help a developer overcome some of the common issues faced in client side ...

This presentation is an effort to combine all the cool features present in Angular and provide a basic idea about how it would help a developer overcome some of the common issues faced in client side development.



Total Views
Views on SlideShare
Embed Views



0 Embeds 0

No embeds



Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

    Introduction to Angular JS Introduction to Angular JS Presentation Transcript

    • An Introduction to a Powerful Framework Santhosh Kumar
    • What is Angular JS • A JavaScript framework (not for the faint hearted) • Simple to develop complex applications • Completely extensible • Extremely flexible • MVC Framework
    • How is it different • Does not crave for control • Perfectly happy to work within your boundaries • Not greedy, can work with other libraries • Do not force you to use it mandatorily for your complete app • Lets you decide where its required and where its not
    • When Should you use it • Scripts expanding at a rapid pace • Too many UI Bindings • Too many heavy lifting on the client side • Completely restful web applications • Single page web applications
    • A Little Comparison JQuery Mark up: <input type=“text” id=“firstName” /> <div id=“firstNameBind”></div> Script: $(function(){ $("#firstName").keyup(function(){ $("#firstNameBind").html($("#firstName").val()); }); });
    • Lets do it the angular way Angular Mark up: <input type=“text” ng-model=“rate.amount” /> <div>{{ rate.amount }}</div> Script: function OpController($scope) { $scope.rate = { amount: 0 } }
    • Things to Note • Identifiers in the form of ID or Class or any other form is not required in Angular • Explicit bindings are not required • $scope is directly used without the need to create it • More natural syntax • Data driven
    • Getting Started • Download the full/minified version of Angular from <script src=“angular.js”></script> • Using Google CDN <script src=""> </script>
    • Specifying App Boundaries <html ng-app> <head> <title>Shopping Cart</title> <body > <div ng-controller='CartController'> <h1>Your Order</h1> <div>Total: {{bill.totalCart | currency}}</div> <div>Discount: {{ | currency}}</div> <div>Subtotal: {{bill.subtotal | currency}}</div> </div> </body> </html>
    • Everywhere ng-app touches… • Ng-app specifies the overall boundary of the Application that will be used by angular • Ng-controller specifies the region that will be controlled by a specific controller
    • $scope • $scope is an object that can be injected anywhere • Most data transitions happen through $scope • It does not have to be created or instantiated • It is available to be used directly through Angular dependency injection
    • Dependency Injection • Objects are injected when ever it is required only at the time it is required • Lets you concentrate on important logic and not the dependencies that affect the behaviour • Angular is built completely on this principle • Law of Demeter • Principle of Least Knowledge
    • $scope is not the chosen one • Many objects can be requested by adding it to the constructor • $scope is not the only one • $location, $route or even the directives we define can be requested via dependency injection by specifying in the constructor
    • Events the Angular Way <form ng-submit="requestCash()" ngcontroller=“AccountController"> Amount: <input ng-change=“balanceCheckNeeded()" ngmodel=“currentDeposit"> Balance: {{availableBalance}} <button>Withdraw!</button> <button ng-click=”showLedger()">Ledger</button> </form>
    • Hold your horses • Don’t hate declarative events • These are not the HTML events you are looking for • These are Angular Directives • No! We are not back to square one
    • They are still unobtrusive • Cross Browser Compatibility • All heavy lifting done by angular • Events do not operate in global namespace • They work within their own scope of the parents controller
    • Markup: <div class=“sectionbar" ng-controller=“SectionController"> … <li class="menu-item" ng-click="doSomeFunc()">Click Me</li> … </div> <div class="mainArea" ng-controller="MainAreaController"> … <div ng-click=" doSomeFunc()">...</div> … </div> Script: function SectionController($scope) { $scope.doSomeFunc = doA; } function MainAreaController($scope) { $scope.doSomeFunc = doB; }
    • So that’s how it works • Mapping the right functions for the right events is automatically handled by Angular • No explicit directive other than the controller references is required • Declarative events reduce the hassle of fiddling with IDs and Classes • Still it doesn’t violate any best practices
    • Modular Approach • Angular is completely modular • Namespaces allows perfect separation of application logic • Avoids need for conflict resolution in terms of similar objects
    • <html ng-app='myApp'> <head> <title>Shopping Cart</title> <body > <div ng-controller=‘ShopController'> <h1>Your Order</h1> </div> </body> </html> Script: var myAppModule = angular.module('myApp',[]); myAppModule.controller(‘ShopController',function($scope){ $scope.menuState = { show : false}; });
    • Useful Directives
    • Ng-Repeat Mark up: <div ng-repeat='item in items'> <span>{{item.title}}</span> <input ng-model='item.quantity'> <span>{{item.price | currency}}</span> <span>{{item.price * item.quantity | currency}}</span> <button ng-click="remove($index)">Rfmove</button> </div> Script: myAppModule.controller('CartController', function($scope) { $scope.items = [ {title: 'Paint Pots1', quantity: 8, price: 3.95}, {title: 'Paint Pots2', quantity: 18, price: 12.95}, {title: 'Paint Pots3', quantity: 5, price: 6.95}, ]; });
    • Event Directives • • • • • • • Ng-click Ng-dblclick Ng-submit Ng-bind Ng-show Ng-hide Ng-change
    • Double Curly Notation • Angular way of defining expression • May contain object references {{ account.balance }} • May point to variables which resolve to a value {{ myAccountBalance }} • May contain simple math expressions {{ currentTotal – accountBalance }}
    • Note • • • • The values within double curly are not evaluated using eval They are evaluated by angular as special expression They cannot contain loops, conditional constructs They maintain state of the variable when there is a model binding
    • Observer and Binding • $scope object called $watch • Once invoked keeps track of changes to an object • Can invoke a method when a change has been detected • Extremely useful to maintain object state when the object is modified from several different locations • Can watch an object, expression or a string that resolves to an object
    • How it works myAppModule.controller(‘TaskController', function($scope) { $scope.tasks = { pendingTask: 0}; taskCompleted = function() { $scope.task.status = !$scope.task.isResolved; }; $scope.$watch(‘task.pendingTask', taskCompleted); }); • taskCompleted is invoked when ever there is a change in pendingTask • Change can effect from any source, direct or binded • Updates all binded dom elements automatically without explicit binding
    • Usage Warning With great power comes great responsibility -Spiderman’s Uncle • While $watch seems like a powerful object (It really is) its usage must be checked • Watching wrong values may eat up the memory of the application • The expression provided must always be as less expensive as possible
    • Communicating with the Server • Provides $http which contains $get, $post that can be used to communicate with web services • Both the underlying methods as well as the wrappers can be used • Transformations are provided for both request and response • Transformation can be intercepted • Provides interface to handle the XHR requests efficiently
    • XHR has never been so easy $http.get('api/user', {params: {id: '5'} }).success(function(data, status, headers, config) { // Do something successful. }).error(function(data, status, headers, config) { // Handle the error }); Methods available for • GET • HEAD • POST • DELETE • PUT • JSONP
    • Method Chaining with then var currentProfile = fetchServerConfig().then(function(serverConfig) { return fetchUserProfiles(serverConfig.USER_PROFILES, username); }).then(function(profiles) { return profiles.currentProfile; }, function(error) { // Handle errors in either fetchServerConfig or // fetchUserProfiles here }); • Function calls are chained • Functions called sequentially • One error handler to rule them all
    • Angular Tools
    • Yeoman • • Lets you generate a boiler plate with default structure • Structure follows default conventions • Base Config files are automatically generated • Integration with Karma by default • Integration with Test Runners
    • Karma • • Easy to run tests • Provide automated test cover • Generates default specs • Records test results • Jasmine style specs • Can understand angular natively
    • NG Boiler Plate • • • Another easy to use boiler plate with default dependencies • Integrated with build system • Pre Packed with Bootstrap, Font Awesome and Less
    • Angular UI • • Provides multiple extra components not natively part of angular • Pre packed with conventional usage components such as highlighter, events not natively supported by angular and indeterminate checkboxes etc
    • IDE • • Paid with a 30 Day trial • Only IDE I know with an angular JS plugin • Code completion for angular directives • Template completion shortcuts • Browser watch for chrome
    • Batarang • • Chrome extension developed specifically for Angular JS • Easy to debug angular scripts • Identifies expensive bindings automatically • Provides watch windows for service calls • Easy to performance tune larger angular apps
    • Further Read • • •
    • Thank You