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.
1. An Introduction to a Powerful Framework
Santhosh Kumar
Github.com/santhotech
2. What is Angular JS
• A JavaScript framework (not for the faint hearted)
• Simple to develop complex applications
• Completely extensible
• Extremely flexible
• MVC Framework
3. 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
4. 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
5. A Little Comparison
JQuery
Mark up:
<input type=“text” id=“firstName” />
<div id=“firstNameBind”></div>
Script:
$(function(){
$("#firstName").keyup(function(){
$("#firstNameBind").html($("#firstName").val());
});
});
6. 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 }
}
7. 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
8. Getting Started
• Download the full/minified version of Angular from Angularjs.org
<script src=“angular.js”></script>
• Using Google CDN
<script
src="https://ajax.googleapis.com/ajax/libs/angularjs/1.x.x/angular.min.js">
</script>
10. 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
11. $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
12. 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
13. $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
14. 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>
15. 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
16. 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
18. 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
19. Modular Approach
• Angular is completely modular
• Namespaces allows perfect separation of application logic
• Avoids need for conflict resolution in terms of similar objects
24. 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 }}
25. 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
26. 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
27. 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
28. 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
29. 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
30. 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
31. 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
33. Yeoman
• http://yeoman.io/
• 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
35. NG Boiler Plate
• http://joshdmiller.github.io/ng-boilerplate/#/home
• https://github.com/ngbp/ngbp#readme
• Another easy to use boiler plate with default dependencies
• Integrated with build system
• Pre Packed with Bootstrap, Font Awesome and Less
36. Angular UI
• http://angular-ui.github.io/
• 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
37. IDE
• http://www.jetbrains.com/webstorm/
• 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